2016-10-01 4 views
0

私はこのようないくつかのコードを記述してみました:TypeScriptで2D配列にガードを入力するにはどうすればいいですか?

const x: string[] | string[][] = blah(); 
if (Array.isArray(x[0])) { 
    // I expect x to be inferred to be string[][] here, but it's not! 
} 

これは、2次元配列であることをxを推測することはありませんどのように来ますか?私は何か間違っているのですか、それともTypeScriptですか?

答えて

1

これらの特定のユニオンを入力する方法はありません。ここでは取り上げ

/** Custom type guard */ 
const isArrayArray = (x): x is string[][] => Array.isArray(x[0]); 

const x: string[] | string[][] = []; 
if (isArrayArray(x)) { 
    // x:string[][] 
    x; 
} 

もっと

ユーザ定義のガード:https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

それはあなたが非常に簡単にカスタム型ガード機能を作成することができました
関連する問題