gpt4 book ai didi

javascript - TS2538 类型 'undefined' 不能用作索引类型。当检查分配给变量时

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:35 25 4
gpt4 key购买 nike

我收到 TS 错误:

TypeScript error: Type 'undefined' cannot be used as an index type. TS2538

对于这个简单的函数(根据提供的索引从数组中获取对象):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
const isIndex : boolean = typeof index !== 'undefined';

return isIndex ? myArr[index] : {};
}

对我来说更神秘的是,当我把它改成:

function getData(index?: number) {
return typeof index !== 'undefined' ? myArr[index] : {};
}

一切都像一个魅力 - 为什么?

最佳答案

由于代码流中的间接性,Typescript 不会按预期执行代码分析。这是用户定义的类型保护来挽救局面的时候。

function isUndefined(index: any): index is boolean {
return typeof index === "undefined";
}

function getData(index?: number) {
return isUndefined(index) ? myArr[index] : {};
}

因为索引在 getData 方法中是可选的,所以它有可能是 undefined,您的第二种方法有效。

关于javascript - TS2538 类型 'undefined' 不能用作索引类型。当检查分配给变量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56355117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com