ユニオン型 (union type)
TypeScriptのユニオン型(union type)は「いずれかの型」を表現するものです。
ユニオン型の型注釈
ユニオン型の型注釈は、2つ以上の型をパイプ記号(|)で繋げて書きます。たとえば、number型もしくはundefined型を表す場合は、number | undefinedのように書きます。
tsletnumberOrUndefined : number | undefined;
tsletnumberOrUndefined : number | undefined;
|は型のリストの冒頭に置くこともできます。型ごとに改行するときに、列が揃うので便利です。
tstypeErrorCode =| 400| 401| 402| 403| 404| 405;
tstypeErrorCode =| 400| 401| 402| 403| 404| 405;
配列要素にユニオン型を使う際の書き方
配列の要素としてユニオン型を用いる場合は、書き方に注意が必要です。たとえば、stringまたはnumberからなる配列の型を宣言することを考えてみましょう。stringまたはnumberをユニオン型で表現するとstring | numberになります。配列型は要素の型に[]をつけて表現します。これをそのまま繋げて考えると、次のような型を思いつくかもしれませんが、これは間違いです。
tstypeList = string | number[];
tstypeList = string | number[];
これはstring型またはnumber[]型であることになっているためです。正しくは以下です。特に配列をT[]形式で書いているときは()が必要になるので注意してください。
tstypeList = (string | number)[];
tstypeList = (string | number)[];
ユニオン型と絞り込み
ユニオン型string | nullがstringなのかnullなのかを判定したいときは、TypeScriptの絞り込み(narrowing)を用います。絞り込みをするにはいくつかの方法がありますが、代表例はif文です。条件分岐で変数がstring型かどうかをチェックすると、同じ変数でも分岐内ではstring | null型がstring型だと判定されます。
tsconstmaybeUserId : string | null =localStorage .getItem ("userId");constType 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.2322Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.: string = userId maybeUserId ; // nullかもしれないので、代入できない。if (typeofmaybeUserId === "string") {constuserId : string =maybeUserId ; // この分岐内では文字列型に絞り込まれるため、代入できる。}
tsconstmaybeUserId : string | null =localStorage .getItem ("userId");constType 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.2322Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.: string = userId maybeUserId ; // nullかもしれないので、代入できない。if (typeofmaybeUserId === "string") {constuserId : string =maybeUserId ; // この分岐内では文字列型に絞り込まれるため、代入できる。}
📄️ 制御フロー分析と型ガードによる型の絞り込み
TypeScriptは制御フローと型ガードにより、処理の流れに応じて変数の型を絞り込むことができます。
関連情報
📄️ 判別可能なユニオン型
TypeScriptの判別可能なユニオン型は、ユニオンに属する各オブジェクトの型を区別するための「しるし」がついた特別なユニオン型です。オブジェクトの型からなるユニオン型を絞り込む際に、分岐ロジックが複雑になる場合は、判別可能なユニオン型を使うとコードの可読性と保守性がよくなります。