简体   繁体   English

Typescript 自定义类型守卫和数组操作

[英]Typescript custom type guards and array operations

Sorry if this is a duplicate but I couldn't find the answer I am looking for.抱歉,如果这是重复的,但我找不到我正在寻找的答案。

I am starting to experiment with TypeScript and I came across used-defined type guards .我开始尝试使用 TypeScript 并且遇到了used-defined type guards I wanted to use them to check if an array is empty but I can't figure out how to do it properly.我想用它们来检查一个数组是否为空,但我不知道如何正确地做到这一点。 This is what I tried so far.这是我到目前为止所尝试的。

function isEmpty<T>(array: Array<T>): array is [] {
  return array.length === 0;
}  

const arr = ['a', 'b', 'c'];
const result: string[] = [];

while (!isEmpty(arr)) {
  result.push(arr.pop())
  //          ^^^^^^^^^ Type error here because pop() returns string or undefined if the array is empty 
}

It seems that TypeScript is unable to narrow down the return type of Array.prototype.pop() as it doesn't have access to its implementation and just relies on the function's signature.似乎 TypeScript 无法缩小 Array.prototype.pop() 的返回类型,因为它无法访问其实现并且仅依赖于函数的签名。

Is there a way to make this work?有没有办法使这项工作? I am most interested in readability and type safety.我对可读性和类型安全最感兴趣。 Thank you for your time感谢您的时间

You need to use type assertion to tell the compiler what will the type of items arr.pop() return be because arr could be empty and the type of result variable is an array of strings.您需要使用类型断言来告诉编译器arr.pop()返回的项目类型是什么,因为arr可能为空并且结果变量的类型是字符串数组。 So the code will look like this:所以代码将如下所示:

const isEmpty = <T>(array: T[]): array is [] => {
  return array.length === 0;
};

const arr = ["a", "b", "c"];
const result: string[] = [];

while (!isEmpty(arr)) {
  result.push(arr.pop() as string);
}

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

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