English 中文(简体)
Array.lengtheck issue: 这一比较似乎无意中,因为第一类和第二类没有重叠[重复]。
原标题:Array.length check issue: This comparison appears to be unintentional because the types 1 and 0 have no overlap [duplicate]
  • 时间:2024-05-14 05:09:29
  •  标签:
  • typescript

体积有以下文字:

const x = [1];

if (x.length !== 1)
throw "error";

x.pop();

if (x.length === 0)
throw "error";

compliler Weirdly在if(x.length=0)上提出申诉。 这一比较看来是无意的,因为第一类和第二类没有重叠。

似乎在第一个条件之后,它总是假定时间为1,而阵列修改并没有改变。 我不理解理由,也不知道我们如何解决这一问题?

游乐联系:

问题回答

This is one of these cases when TypeScript s type narrowing isn t the smartest. TypeScript doesn t follow .length changes through methods, so its way of narrowing the .length type to a union often does not make much sense.

不幸的是,你需要工作。 其中一项是确定新期限,而不是偷窃:

if (x.length > 0) { // This is needed, as an error would be thrown for an empty array
    x.length -= 1; // works like x.pop() minus returning the last item
}

The following code

if (x.length !== 1) throw "error";

narrows down the type of x.length to be 1.

就第二个问题而言,只在Java的运行时间控制流动结构上才有缩小类型,如:





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...