简体   繁体   English

TypeScript 之前检查的未定义值错误

[英]TypeScript error on undefined value that is checked before

I created a function that either adds an item to an array or updates an item to a given index if set.我创建了一个 function ,它要么将项目添加到数组中,要么将项目更新到给定的索引(如果设置)。

I'm using TypeScript and I found a really strange behavior that I can't seem to understand.我正在使用TypeScript ,我发现了一个我似乎无法理解的非常奇怪的行为。

Here is a Playground Link .这是一个游乐场链接

This simplified function is fine for TypeScript:这个简化的 function 适用于 TypeScript:

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

Now if I use a const and store either the index is defined or not so I can use it later on:现在,如果我使用const并存储index是否已定义,以便以后可以使用它:

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

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

TypeScript throws an error pointing at the index inside the Object.assign : TypeScript 抛出指向Object.assign内的索引的错误:

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

And I can't understand why...而且我不明白为什么...

Consider such a case考虑这样一个案例

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

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

Now even if index is undefined , isIndexDefined will be true so this code will run Object.assign([], initialArray, { [index]: item }) and it will fail, because index of Array can not be undefined.现在即使 index 是undefinedisIndexDefined也会是true ,所以这段代码将运行Object.assign([], initialArray, { [index]: item })并且它会失败,因为 Array 的索引不能是未定义的。 (That is what TS is warning you about). (这就是 TS 警告您的内容)。

TS can not make an assumption about your variables before if statement. TS 无法在if语句之前对您的变量做出假设。

In the first case, you check for undefined directly in if like if (index !== undefined) and in this case it is clear for TS that in true case your index is a number.在第一种情况下,您直接在if (index !== undefined)中检查未定义,在这种情况下,TS 很清楚,在true情况下您的index是一个数字。

So possible solutions:所以可能的解决方案:

  • check for undefined inside if statement (preferred)检查 if 语句内部的未定义(首选)
  • write [index as number], only if you are sure (if someone will change code before if, TS will not detect an error)写[index as number],只有在你确定的情况下(如果有人在if之前更改代码,TS不会检测到错误)

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

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