Partial
type Partial<T> = { [P in keyof T]?: T[P]; }で定義されてます。Tはオブジェクトです。全部のプロパティを?:へ変換しています。これによりすべてのプロパティが省略できる新しい型が取得できます。
type Foo = {
value: string;
};
type Result = Partial;
// type Result = { value?: string; } Required
type Required<T> = { [P in keyof T]-?: T[P]; }で定義されてます。これはPartialの完全に逆です。そのオブジェクトが持っている?:なプロパティを:へ変換した新しい型が取得できます。
type Foo = {
value?: string;
};
type Result = Required;
// type Result = { value: string; } Record
type Record<K extends string | number | symbol, T> = { [P in K]: T; }で定義されてます。オブジェクトの値の型(T)がすべて同じ時に、それらプロパティ(K)の型をすべてTとなるようにまとめて定義することができます。
type Result = Record<'foo' | 'bar' | 'baz', string>;
// type Result = {
// foo: string;
// bar: string;
// baz: string;
// }Pick
type Pick<T, K extends keyof T> = { [P in K]: T[P]; }で定義されてます。ある Interface からその型だけの新たな Interface を作ります。
interface Values {
foo: string;
bar: number;
baz: boolean;
}
type Result = Pick
// type Result = { foo: string; } Omit
(TypeScript v3.5 から)これはPickの逆の動きをします。
interface Values {
foo: string;
bar: number;
baz: boolean;
}
type Result = Pick
// type Result = { bar: number; baz: boolean } Exclude
type Exclude<T, U> = T extends U ? never : Tで定義されてます。TとUは文字列リテラル Union 型でTとUを比較し、Tにしかない文字列リテラル (Union) 型を返します。
type Result = Exclude<'foo' | 'bar' | 'qux', 'foo' | 'baz'>;
// type Result = 'bar' | 'qux'TypeScript v3.5 以前ではOmit型の代わりに使うことができます。
interface Values {
foo: string;
bar: number;
baz: boolean;
}
type Result = Pick>
// type Result = { bar: number; baz: boolean } Extract
type Extract<T, U> = T extends U ? T : neverで定義されてます。Excludeに似てますが、こちらは両方にある文字列リテラル (Union) 型を返します。
type Result = Extract<'foo' | 'bar' | 'qux', 'foo' | 'baz'>;
// type Result = 'foo'NonNullable
type NonNullable<T> = T extends null ? never : Tで定義されてます。Tは何でも受け取れます。もしそのTが Union でnullやundefinedを含んでいる場合、それらを取り除いてくれます。
type Result = NonNullable;
// type Result = true | 1 | 'a' ReturnType
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : anyで定義されてます。Tは関数型になります。これはTの戻り値の型を取得できます。
type Result = ReturnType<() => number>;
// type Result = numberInstanceType
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : anyで定義されてます。Tにはクラスを渡してそのインスタンスの型を取得できます。
class Foo {
static staticMethodFn() {}
methodFn() {}
}
type Result = InstanceType;
// type Result = Foo ( === {methodFn() {}} ) DateConstructor
interface DateConstructor {
new (value: number | string | Date): Date;
}DateDateConstructor['new']InstanceTypeDate
type Date = InstanceType;
// type Date = Date