TypeScript 合併型について
以下のような型があるとします。
type Hoge = {
name: string
code: string
}
type Foo = {
name: number
code: number
}
この型を引数にとる関数myFuncを以下のように定義した場合、if文の中ではcodeはstringになりそうだが、実際はstring|numberになる。
const myFunc = (value: Hoge | Foo) => {
if(typeof value.name === 'string') {
value.code // 実際は string | number
}
}
これは、Hoge | Foo というのが Hoge または Foo という意味ではないため。
型を絞りたい場合は、以下のようにリテラル型でタグをつけると良い。
type Hoge = {
type: 'hoge'
name: string
code: string
}
type Foo = {
type: 'foo'
name: number
code: number
}
const myFunc = (value: Hoge | Foo) => {
if(value.type === 'hoge') {
value.code // string
}
}
最近のコメント