1

Backbone Demo

const DirectedPropertySets = {
    start: ["left", "top"] as const, // for DOMRectReadOnly
    client: ["clientX", "clientY"] as const // for PointerEvent
};

type DirectedPropertySet<T> = {
    [P in keyof typeof DirectedPropertySets]: typeof DirectedPropertySets[P][0] extends keyof T ? P : never;
}[keyof typeof DirectedPropertySets];

/**
 * One of usage of this whole thing to show you why I'm making things like this
 * Don't be bothered by this
 */
function getFromRect(rect: DOMRectReadOnly, key: DirectedPropertySet<DOMRectReadOnly>) {
    const set = DirectedPropertySets[key];
    /**
     * const set: readonly ["left", "top"]
     */
    return rect[set[0]]; // fine
}

/**
 * This is the issue that produces an error
 */
function getFromEvent<T extends Event>(event: T, key: DirectedPropertySet<T>) {
    const set = DirectedPropertySets[key];
    /**
     * const set: {
     *      start: readonly ["left", "top"];
     *      client: readonly ["clientX", "clientY"];
     * }[DirectedPropertySet<T>]
     */
    return event[set[0]]; // error
}

/**
 * The previous one that has a change not to produce an error
 */
function getFromEvent<T extends Event>(event: T, key: DirectedPropertySet<Event>) {
    const set = DirectedPropertySets[key];
    /**
     * const set: never
     * it's okay to have type of never as I intended it
     */
    return event[set[0]]; // fine
}

From how the type of local variable set changes depending on the type of the parameter key, I think that DirectedPropertySet<T> in key: DirectedPropertySet<T> just refer to the definition of the type DirectedPropertySet<T> rather than actually applies the generic type T extends Event into DirectedPropertySet<T>.

What am I mistaking about Typescript's generic type?

From @jcalz's request, I'll demonstrate my actual usage of it as simply as possible. You'll see that actually there is another parameter in getFromEvent.

// "pointermove" event listener
function onPointerMove(ev: PointerEvent) {
    /**
     * Only "client" is visible,
     * which means DirectedPropertySet<T> of getFromEvent is resolved,
     * but then why the DirectedPropertySets[key][axis]
     * can't index "event" parameter of getFromEvent?
     */
    const ... = getFromEvent(ev, "client", 0);
    ...
}

// parameter "axis" is added to index DirectedPropertySets[key]
function getFromEvent<T extends Event>(event: T, key: DirectedPropertySet<T>, axis: number) {
    const property = DirectedPropertySets[key][axis];
    // return event[property]; // produces an error
    return event[property as Extract<typeof property, keyof T>];
}

Typescript's lead developer answered about this issue.

(Note that I gave him a different example, so type names and type declarations are a bit different.)

There's no way for TS to realize that the only kinds of things that can come out of Intersecting are keyof Ts

I understood this as TS cannot resolve some complicated parameter types.

10
  • 2
    It would be much easier for someone else to help you if you could minimize to a minimal reproducible example so that it does not include anything we don't need to pay attention to. I see that you say you tried, but you might want to try again? I imagine this will eventually be something where the compiler simply cannot follow the higher order type manipulation of an unspecified generic type parameter and you'll need to use a type assertion or the like if you want to silence the compiler error and move forward.
    – jcalz
    Feb 10, 2021 at 16:53
  • 1
    Agree with @jcalz, please provide minimum reproducible example. It requires a lot of time to figure out whats goin on here Feb 10, 2021 at 18:12
  • 1
    I can sum it up for @jcalz and @captain-yossarian but I don't think I can give you a good answer other than that TS is smart enough for this. Basically the complicated DirectedPropertySet<T> type resolves to either "client" or "client" | "marginEnd". It will ONLY include "marginEnd" as a possibility if the event type T has both marginRight and marginBottom. We get an error when accessing a property that could be marginRight on an event T because not all Ts will have this property, but the property k[0] can only ever be marginRight in cases where it DOES exist on T. Feb 11, 2021 at 0:37
  • 1
    I don't understand how you plan to call getFromEvent(), though. Can you include some simple calls so I can see what you're trying to support? Clearly you care about the correlation between the first and second arguments, but I would like to see use cases to know if I can change the signatures to provide a better experience.
    – jcalz
    Feb 11, 2021 at 1:52
  • 1
    Without understanding what's going on here, I'd suggest a change like this because of an issue where property lookups with unresolved generics sometimes get eagerly evaluated when we'd like them to be deferred to stay generic, as in possibly-related microsoft/TypeScript#33181. If that works for you I'll write up an answer; otherwise, please do elaborate by showing how you intend to call this thing.
    – jcalz
    Feb 11, 2021 at 2:04

1 Answer 1

1

The general reason why this is happening has to do with whether the compiler defers evaluation of a type that depends on an as-yet unspecified generic parameter (like the T parameter inside the implementation of getFromEvent()), or whether it eagerly evaluates it. I don't really know the details of the heuristics the compiler uses to make the determination, but I'll briefly mention the pros and cons of both and why it's a hard problem. See this comment on microsoft/TypeScript#33181 for some more information.


When the compiler defers evaluation of a type, you will eventually get quite a precise type once the generic type parameter is specified. That's good. But before this happens, the compiler mostly doesn't know whether or not any given value is assignable to it. So if you try to make/return a value of such a type, the compiler will most likely produce a warning, even if you know it's safe. That's bad. For example:

type KeysMatching<T, V> = NonNullable<
  { [K in keyof T]: T[K] extends V ? K : never }[keyof T]
>;
interface Foo {
  a: string,
  b: number,
  c: boolean
};
type StringFoo = KeysMatching<Foo, string> // "a"

Here, KeysMatching<T, V> will take an object type T and return any keys whose properties are assignable to V. So StringFoo is just "a". But inside a generic function where T is generic, the compiler cannot follow it:

function foo<T>(t: T, k: KeysMatching<T, string>): string {
  return t[k]; // error! 
  // 'T[NonNullable<{ [K in keyof T]: T[K] extends string ? K : never; }[keyof T]>]'
  //  is not assignable to type 'string'
}

Here, the type is deferred: and while it turns out to be true that T[KeysMatching<T, string>] should be assignable to string, this would be a higher-order type analysis that the compiler just cannot do. So you get an error. If you want to work around that, you might need a type assertion:

return t[k] as any as string; // 🤷‍♂️

When the compiler eagerly evaluates an unspecified generic type, it essentially gives up on correctness and just plugs the generic constraint in for the generic type. So if T extends Foo, then T gets replaced with Foo. This isn't always correct, and even when it is correct, it's often less precise than it could be. But it's convenient, and the compiler lets you assign things to it... even if that might be unsafe to do so. Here's an example:

function bar<T extends Foo>(foo: T) {
    foo.b = 1; // uh oh, foo.b is eagerly evaluated as number
}

interface ZeroB extends Foo { b: 0 };
const zeroB: ZeroB = { a: "", b: 0, c: true };
bar(zeroB); // oops!  zeroB.b is now 1 at runtime but the compiler thinks it's zero

Inside bar(), the property type foo.b is eagerly evaluated by the compiler to be Foo['b'], which is number, even though it technically should be T['b']. If you have a type like ZeroB which matches Foo but has a b property that can only be the numeric literal 0, and pass a value of that type into bar(), something bad happens. It was convenient to allow number to be assigned to foo.b, but unsafe.


Anyway, with your example code, the problem seems to be that the type of DirectedPropertySets[key][axis] is eagerly evaluated. The type T is replaced with Event (or possibly never if the constraint is contravariant), and so DirectedPropertySets[key][axis] is seen as something like "left" | "top" | "clientX" | "clientY". This is not known to be a key of T, so there's an error.

Ideally you'd like the compiler to defer the type, although you might have to convince it that the access is safe. To do this I will add more generic type parameters to aid in the deferral, and a type assertion to prevent errors:

function getFromEvent<T extends Event, K extends DirectedPropertySet<T>, A extends number>(
    event: T, key: K, axis: A) {

    const property = DirectedPropertySets[key][axis];
    /* {
    start: readonly ["left", "top"];
    client: readonly ["clientX", "clientY"];
    }[K][A] */

    return event[property as Extract<keyof T, typeof property>];    
}

Here all three function inputs are given their own type parameter, and so property is duly deferred to be something like (typeof DirectedPropertySets)[K][A]. This is still not understood to be assignable to keyof T, so I use an assertion to tell the compiler it can treat property as both keyof T and the deferred typeof property (using the Extract<T, U> utility type).

Now everything works as expected, I think. The return type of the function is the rather unwieldy

T[Extract<keyof T, {
    start: readonly ["left", "top"];
    client: readonly ["clientX", "clientY"];
}[K][A]>]

but if you plug in specific types for T, K, and A, it will work:

function onPointerMove(ev: PointerEvent) {
    const d = getFromEvent(ev, "client", 0); // number
}

Note that the assertion above might be a bit incorrect... if the type of T is something crazy like like Event & {clientX: Date}, then this happens:

function hmm(ev: Event & { clientX: Date }) {
    const d = getFromEvent(ev, "client", 1); // never!
}

The compiler sees that ev does not have a clientY property and returns never from getFromEvent(). This isn't exactly true; it would probably be undefined. There might be ways around this, but the answer is already very long and I don't want to make it longer. Suffice it to say that you should tread carefully when dealing with the implementation of generic functions.

Playground link to code

3
  • Wow I didn't think you'd explain it in this detail. I really appreciate it! By the way, I found that you used the word contravariant in your answer and on some github threads. I searched for the concept, but I still don't get it. Have you written an article explaining the concept or do you know an web page that explains it well? Feb 13, 2021 at 18:37
  • 1
    Maybe this one will explain it?
    – jcalz
    Feb 13, 2021 at 21:51
  • Oh that makes it clear! I got it thank you :) Feb 14, 2021 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.