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 = number
InstanceType
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;
}
Date
DateConstructor['new']
InstanceType
Date
type Date = InstanceType;
// type Date = Date