type T1 is Tuple, T2 is Object. but I think their implementation methods are the same.
type Tup = ['a','b']
type Options <T> = {
[K in keyof T]: 1
}
type T1 = Options<Tup> // type T1 = [1, 1]
type keys1 = keyof Tup
type T2 = {
[K in keys1] :1
}
/**
* type T2 = {
[x: number]: 1;
[Symbol.iterator]: 1;
0: 1;
1: 1;
[Symbol.unscopables]: 1;
length: 1;
...
}
*/
I want to know how TypeScript handles these two types separately, and what is the reason for this
In
T1
, TypeScript knows thatT
is a tuple, so the result should be a tuple. InT2
, TypeScript only has the keys to work with and doesn’t know that it is supposed to be a tuple.It has to do with whether the mapped type is homomorphic. A homomorphic mapped generic like
type F<T> = {[K in keyof T]: ⋯}
will map tuples to tuples, but a non-homomorphic type will not. See the answers to the linked questions for more information.