18
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptのArray#filterでType Guard(Like Smart Cast)する

Last updated at Posted at 2017-09-10

普通に書く

let arr1:(number|string)[]=['a','b','c',1,2,3];
let arr2=arr1.filter(x=>typeof x==='string');

arr2にはstringしか入ってないはずなのに型は(number|string)[]になってしまいます。

型ガード

let arr2 = arr1.filter<string>((x): x is string => typeof x === 'string');

これでarr2はstring[]になります。

注意

let arr2=arr1.filter<number>((x): x is number => typeof x === 'string');

このような事をしてもコンパイルエラーにはなりません。
arr2の実際の型はstring[]なのにTypeScriptはnumber[]と認識します。
キャストと同じように危険な操作なので注意しましょう。

他のライブラリ

immutable.jsやrxjsでも似たような事を出来ます。

18
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?