「TypeScript」union(共用体)で複数の型を許容する

2021年11月10日

環境
Windows10 64bit
TypeScript Version 4.4.4

書式
let 変数名:型1 | 型2
var 変数名:型1 | 型2
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//union共用体で複数の型を許容する
let cft: number | string| boolean;
cft = 'study'
console.log("union共用体のサンプル")
console.log(cft)
cft = 567
console.log(cft)
cft = false
console.log(cft)
//union共用体で複数の型を許容する let cft: number | string| boolean; cft = 'study' console.log("union共用体のサンプル") console.log(cft) cft = 567 console.log(cft) cft = false console.log(cft)
//union共用体で複数の型を許容する
let cft: number | string| boolean;

cft = 'study'
console.log("union共用体のサンプル")
console.log(cft)
cft = 567
console.log(cft)
cft = false
console.log(cft)

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
union共用体のサンプル
study
567
false
union共用体のサンプル study 567 false
union共用体のサンプル
study
567
false

 

TypeScript

Posted by arkgame