2016-10-01 105 views
0

我試着寫一些像這樣的代碼:如何在TypeScript中的二維數組上輸入guard?

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

怎麼會不能由此推斷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