
TypeScriptの共用体型(Union Type)とは?初心者向けに解説
TypeScriptを使用すると、
変数または関数パラメーターに複数のデータ型を使用できます。
これを、共用体型(Union Type)と呼びます。
Syntaxとしてはこんな感じです。
(type1 | type2 | type3 | .. | typeN)
次の共用体タイプの例を考えてみましょう。
let code: (string : number);
code = 123; //ok
code = "ABC" //ok
code = false //コンパイルエラー
let empId: string | numberl;
empId = 111; //ok
empId = "E111" //ok
exmId = true //コンパイルエラー
こんな感じで複数のデータ型を定義できましたね。
また、関数パラメーターも共用体(Union Type)タイプにすることもできます。
function displayType(code: (string | number))
{
if(typeof(code) === "number")
console.log("Code is number")
else if(typeof(code) === "string")
console.log("Code is string")
}
displayType(123); // Output: Code is number.
displayType("ABC"); // Output: Code is string.
displayType(true); //コンパイルエラー: Argument of type 'true' is not assignable to a parameter of type string | number
こんな感じですね。
stringかnumberを受け取れるユニオンタイプの関数を定義することが出来ました。
*参考記事