gpt4 book ai didi

javascript - 之前检查的未定义值出现 TypeScript 错误

转载 作者:行者123 更新时间:2023-12-02 20:57:51 27 4
gpt4 key购买 nike

我创建了一个函数,可以将项目添加到数组中,或者将项目更新到给定的索引(如果已设置)。

我正在使用 TypeScript,我发现了一种我似乎无法理解的非常奇怪的行为。

这是一个Playground Link .

这个简化的函数非常适合 TypeScript:

function OKAddOrUpdateFunction(item: string, index?: number) {
const foo = index !== undefined
? Object.assign([], initialArray, { [index]: item }) : [...initialArray, item];
}

现在,如果我使用 const 并存储 index 是否已定义,以便稍后使用它:

function NOKAddOrUpdateFunction(item: string, index?: number) {
const isIndexDefined = index !== undefined;

const foo = isIndexDefined
? Object.assign([], initialArray, { [index]: item }) : [...initialArray, item];
}

TypeScript 抛出一个错误,指向 Object.assign 内的索引:

(parameter) index: number | undefined
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.(2464)

我不明白为什么......

最佳答案

考虑这样的情况

function NOKAddOrUpdateFunction(item: string, index?: number) {
const isIndexDefined = index !== undefined || true; // always true

const foo = isIndexDefined
? Object.assign([], initialArray, { [index]: item }) : [...initialArray, item];
}

现在,即使索引未定义,isIndexDefined 也将为 true,因此此代码将运行 Object.assign([], initialArray, { [index]: item }) 并且会失败,因为数组的索引不能是未定义的。 (这就是 TS 警告您的内容)。

TS 无法在 if 语句之前对变量做出假设。

在第一种情况下,您可以直接在 if 中检查未定义,如 if (index !== undefined) ,在这种情况下,对于 TS 来说,在 true 中很清楚如果您的 index 是一个数字。

可能的解决方案:

  • 检查 if 语句内是否未定义(首选)
  • 仅在确定的情况下才写[index as number](如果有人在if之前更改代码,TS将不会检测到错误)

关于javascript - 之前检查的未定义值出现 TypeScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428057/

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