简体   繁体   English

如何在TypeScript中在2D数组上键入保护?

[英]How to type guard on a 2D array in TypeScript?

I tried to write some code like this: 我试图写一些这样的代码:

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

How come this doesn't infer x to be a 2D array? 为什么这不能推断x为2D数组? Am I doing something wrong, or is TypeScript? 我是在做错什么,还是TypeScript?

there isn't a ways to type guard those particular unions. 没有办法保护那些特定的联合体。 That said you can create a custom type guard function quite easily: 也就是说,您可以轻松创建自定义类型保护函数:

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

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

More 更多

user defined guards covered here : https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html 用户定义的警卫涵盖在这里: https : //basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM