null
および undefined
を除いた型を取得する
ある型から null
および undefined
を除いた型を取得するには
NonNullable<T>
を使うとよい。
公式サイトに記載されている例
type T0 = NonNullable<string | number | undefined>; // string | number
type T1 = NonNullable<string[] | null | undefined>; // string[]
ジェネリックな型を non-nullable なものに制限する
ではジェネリックな型を non-nullable なものに制限したい場合はどうすればよいだろうか。
例えば次のような関数で引数 value
を non-nullable なものだけにしたい場合である。
function accept<T>(value: T): void {
// ...
}
このような場合、型パラメータの定義はそのままにして、
non-nullable な型が必要なところで NonNullable
を適用した型を指定すればよい。
function accept<T>(value: NonNullable<T>): void {
// ...
}
動作確認:
function through<T>(value: T): T {
return value;
}
accept(through<string>("")); // OK
accept(through<string | null>("")); // コンパイルエラー!
accept(through<string | undefined>("")); // コンパイルエラー!
/以上