12
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】ジェネリックな型を null でも undefined でもないものに制限する

Posted at

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>("")); // コンパイルエラー!

/以上

12
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?