LoginSignup
1
0

More than 3 years have passed since last update.

TypeScript 共有型の配列の型推論

Last updated at Posted at 2019-11-25

TypeScript v3.6.3
では改善されている模様です。

こちらに記述がなかったと思ったので
https://qiita.com/uhyo/items/6acb7f4ee73287d5dac0

共有型(パイプ|で区切った指定した型のいずれかに一致する値の変数を代入できる型)
の配列の要素を取り出したとき型推論がうまくいかない。

なんらかの変数に一旦代入しておかないといけない。

export type hoge = FOO | BAR;

export typo FOO ={
  kind :"FOO";
  sawa : stinrg;
}
export type BAR={
   kind: "BAR";
   erika:string;
}

//NG
if (hoge[0].kind==='FOO' as const)
{
}
//OK
const homare = hoge[0]
if (homare.kind==='FOO' as const)

}

1
0
2

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
1
0