[英]Typescript custom type guards and array operations
抱歉,如果这是重复的,但我找不到我正在寻找的答案。
我开始尝试使用 TypeScript 并且遇到了used-defined type guards 。 我想用它们来检查一个数组是否为空,但我不知道如何正确地做到这一点。 这是我到目前为止所尝试的。
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
}
似乎 TypeScript 无法缩小 Array.prototype.pop() 的返回类型,因为它无法访问其实现并且仅依赖于函数的签名。
有没有办法使这项工作? 我对可读性和类型安全最感兴趣。 感谢您的时间
您需要使用类型断言来告诉编译器arr.pop()
返回的项目类型是什么,因为arr
可能为空并且结果变量的类型是字符串数组。 所以代码将如下所示:
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.