Mapped Type for array and tuple
Mapped Typeを強化したもの
TypeScript 3.1で入った
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#mapped-types-on-tuples-and-arrays
そもそも存在するMapped Typeを改善したものなので、この挙動に対して固有名詞はないが
https://github.com/Microsoft/TypeScript/pull/26063
このプルリクに習って、このタイトルでページを作った
In TypeScript 3.1, mapped object types over tuples and arrays now produce new tuples/arrays, rather than creating a new type where members like push(), pop(), and length are converted. For example:
code:ts
type MapToPromise<T> = { K in keyof T: Promise<TK> };
type Coordinate = number, number;
type PromiseCoordinate = MapToPromise<Coordinate>; // Promise<number>, Promise<number>
このように、タプルや配列をkeyofすると、配列のpushとかpopとかの関数がkeyとして出現してしまっていたが、そこはよしなに見てindexの数字のみをkeyに取るようにした、というもの
https://qiita.com/Quramy/items/c596b1bacf591da545b2
Array Likeな型のMapped Typeは、その配列の要素に対してマッピングが行われる
ただし、これが動かない場合がある
https://github.com/microsoft/TypeScript/issues/27995
code:ts
type Foo = 'a', 'b';
interface Bar
{
a: string;
b: number;
}
type Baz = { K in keyof Foo: Bar[FooK]; }; // Expected Baz to be string, number
これは動かん
https://github.com/microsoft/TypeScript/issues/27995#issuecomment-433056847
The issue here is that we only map to tuple and array types when we instantiate a generic homomorphic mapped type for a tuple or array.
どうやら、keyofがジェネリックなときだけ動いてて、この状況では現状動かないっぽい?
genericな同型のmapped typeをインスタンス化したときだけ
どういうこと?
https://github.com/microsoft/TypeScript/issues/27995#issuecomment-575006947
code:ts
interface Box<V = unknown> {
value: V
}
function box<V>(value: V) {
return { value }
}
type Unbox<B extends Box> = B'value'
type UnboxAll<T extends Box[]> = {
i in keyof T: Unbox<Extract<Ti, Tnumber>> // !!!
}
declare function unboxArray<T extends Box[]>(boxesArray: T): UnboxAll<T>
declare function unboxTuple<T extends Box[]>(...boxesTuple: T): UnboxAll<T>
const arrayResult = unboxArray(box(3), box('foo')) // (string | number)[]
const tupleResult = unboxTuple(box(3), box('foo')) // number, string
playground
Extract< T[i], t[number]>しないと、こうなる
https://gyazo.com/f6ae552e4e0109bfed606553d4db52a4