typescripttypescript-generics

Why TS generates wrong type after infer and template literal type


Why does the code below output the wrong type?


type Excuse<Excuses extends Record<string, string>> = {
  new (excuses: Excuses): keyof Excuses extends `${infer Key}`
    ? `${Key}: ${Excuses[Key]}`
    : never;
};

const helpingTheReindeer = {
  helping: 'the reindeer',
  differentKey: 'hello'
} as const;

declare const Excuse0: Excuse<typeof helpingTheReindeer>;
const excuse0 = new Excuse0({
  ...helpingTheReindeer,
});
type t0_actual = typeof excuse0;

As we can see t0_actual is "helping: the reindeer" | "helping: hello" | "differentKey: the reindeer" | "differentKey: hello" and not just "helping: the reindeer" | "differentKey: hello". Why?

I asked this question to ChatGpt and it said that TS tries to combine all keys with all values. But why is that? The object is passed as a constant, its value cannot change

You can try it here Playground link

I was solving https://www.adventofts.com/ day 11 and discovered this. I'm waiting for an explanation of why the TS type system behaves the way it does


Solution

  • The type keyof Excuses extends `${infer Key}` ? `${Key}: ${Excuses[Key]}` : never; uses inferring within conditional types to essentially "copy" the union type keyof Excuses (which is "helping" | "differentKey") into the type variable Key (you use a template literal type there but it doesn't do much in this circumstance). So Key is just a union, and when you mention it twice inside `${Key}: ${Excuses[Key]}`, you get the single type `${"helping" | "differentKey"}: ${Excuses["helping" | "differentKey"]}`, and any correlation between "helping" in the first mention of Key and "helping" in the second mention of Key is lost. Thus it expands out to the four element union you don't want.


    What you want to do is distribute the `${Key}: ${Excuses[Key]}` type over unions in Key. So that if Key is A | B then your result is `${A}: ${Excuses[A]}` | `${B}: ${Excuses[B]}`. There are various ways to get this to happen. You could use a distributive conditional type, wrapping `${Key}: ${Excuses[Key]}` with an apparently no-op Key extends unknown ? ⋯ : never:

    type Excuse<Excuses extends Record<string, string>> = {
      new(excuses: Excuses): keyof Excuses extends `${infer Key}` ?
        Key extends unknown ? `${Key}: ${Excuses[Key]}` : never
        : never;
    };
    // type t0_actual = "helping: the reindeer" | "differentKey: hello"
    

    Or, since Key is keylike to begin with, you can use a distributive object type as coined in microsoft/TypeScript#47109, where you make a mapped type over all the keys and then index into it with those keys:

    type Excuse<Excuses extends Record<string, string>> = {
      new(excuses: Excuses): keyof Excuses extends `${infer Key}` ?
        { [P in Key]: `${P}: ${Excuses[P]}` }[Key]
        : never;
    };
    // type t0_actual = "helping: the reindeer" | "differentKey: hello"
    

    I tend to prefer distributive object types because TypeScript "understands" them better. In the above, I probably wouldn't bother with a conditional type at all, since instead of copying keyof Excuses into Key, I'd just map over keyof Excuses directly:

    type Excuse<X extends Record<string, string>> = {
      new(excuses: X): { [Key in keyof X]:
        `${string & Key}: ${X[Key]}`
      }[keyof X];
    };
    // type t0_actual = "helping: the reindeer" | "differentKey: hello"
    

    And the only thing I needed to change was to intersect Key with string inside the template literal type, since keyof X might have symbols (no, X extends Record<string, string> does not prevent symbol-valued keys), and you can't serialize those in template literals.

    Playground link to code