Key Remapping in Mapped Types
from TypeScript 4.1
Key Remapping in Mapped Types
key remapping via as
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as
Mapped Typeの新機能
こう書けるようになった
code:ts
type MappedTypeWithNewKeys<T> = {
K in keyof T as NewKeyType: TK
// ^^^^^^^^^^^^^
// This is the new syntax!
}
mapする際のkey側を変更できるようになった
これは、Template Literal Typesと組み合わせると強い
code:ts
type Getters<T> = {
[K in keyof T as get${Capitalize<string & K>}]: () => TK
};
interface Person {
name: string;
age: number;
location: string;
}
type LazyPerson = Getters<Person>;
// ^ = type LazyPerson = {
// getName: () => string;
// getAge: () => number;
// getLocation: () => string;
// }
さらにremapの際にneverを渡すことで、除外できる
The Omit helper typeみたいなことがその場でできる
code:ts
// Remove the 'kind' property
type RemoveKindField<T> = {
K in keyof T as Exclude<K, "kind">: TK
};
interface Circle {
kind: "circle";
radius: number;
}
type KindlessCircle = RemoveKindField<Circle>;
// ^ = type KindlessCircle = {
// radius: number;
// }
バグ
https://github.com/microsoft/TypeScript/issues/40586
code:ts
type tuple = 0, 1, 2
type Mapped<T> = {
K in keyof T: TK | undefined
}
type MappedAs<T> = {
K in keyof T as K: TK | undefined
}
type test0 = Mapped<tuple> // tuple shape is preserved
type test1 = MappedAs<tuple> // tuple shape is object now
Mapped Type for array and tupleの改善がasを使うと壊れる
TSで型パズル気合い入れるとすぐ使いたくなる割には、バグが昨年から放置されてるな