TypeScript 2.8.3を利用しています。
tscが以下のコードで$t
はstring | true | TestValue[]
だと言い張ります。
TypeScript
1type TestValue = string|true; 2interface Test { 3 [key:string] : TestValue|TestValue[]; 4} 5function isArray($_:any):$_ is TestValue[]{return true;} 6// なんかかんや処理 7if( isArray($Test[$k]) ){ 8 const $t = $Test[$k]; 9}
当然const $t:TestValue[] = $Test[$k];
でも型が合わないのでエラーになります。
以下の様に一旦変数に入れてからTypeGuardを通すと正しく推論されます。
TypeScript
1const $t = $R[$k]; 2if(isArray($t)){ 3 $t;//これだとTestValue[]と認識される 4}
またasで型を強制する事でエラーが出ない様に出来る事も解っています。
TestValue[]
なのは自明に見えるのに何故このような挙動になるのでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。