Why it is allowed to index array with invalid keys in mapped object

Viewed 43

In the following code typescript compiler allows us to index tuple with invalid keys infering unknown for invalid string keys and undefined for invalid number keys. When indexing with an object like Promise<number> tsc infers empty object.

type Foo<T extends any[]> = {
  [K in T[number]] : T[K]
}

/*
  type x = {
      4: undefined;
      toString: () => string;
      abcd: unknown;
      1: "abcd";
  }
*/
type x = Foo<['toString', 'abcd', 1, 4]>
/*
  type y = {
    [x: string]: unknown;
  }
*/
type y = Foo<[string]>
/*
  type z = {
    [x: number]: number;
  }
*/
type z = Foo<[number]>
/*
  type l = {}
*/
type l = Foo<[symbol]>
/*
  type f = {}
*/
type f = Foo<[Promise<number>]>

Why is this allowed? Why removing extends any[] bound produces compile error, that I would expect to see without removing it.

0 Answers
Related