English 中文(简体)
为什么选择链导致“在从来的类型上不存在整批Xxx, 即“部署前错误?
原标题:Why does Optional Chaining lead to "Property xxxxx does not exist on type never " pre-transpilation error?
  • 时间:2023-12-03 20:28:26
  •  标签:
  • typescript

As stated in TypeScript 3.7 reference on optional chaining, we can secure access to properties or methods to possibly null or undefined instances with the ?. notation.

Under TypeScript 4.9.4, tsconfig.json (target: "ES2020" & module: "commonjs"), Visual Studio Code, different situations lead to pre-transpilation errors: "Property xxxxx does not exist on type never ".

let a
let a: string | null = null
let a: string | undefined = undefined

console.log( a?.toString() )   // << "Property  toString  does not exist on type  never "

The only way I had identified it worked is in case of intermediary of function or lambda (arrow function) interfaces:

let lambda = (value: string | null) => {
    console.log(value?.toString())       // << no complaining
}

let a = null
lambda(a)                                // << no complaining

a = "Hello World!"
lambda(a)

在该案中,预审人员没有投诉。

为什么它不像文件所说的那样工作?

问题回答

www.un.org/Depts/DGACM/index_spanish.htm 简短回答:

While the pre-compiler can define the instance is null or undefined it will complain that expectation of test (?.) is always irrelevant. It s simply because the code outcomes to a static situation (invariable) where the instance is null or undefined.

Detailed answer:

当你用optional chaining (?)

let a: string | undefined = undefined;
a?.toString();

......实际做到:

a && a.toString();

符合逻辑的是:

if (a) {
  a.toString();
}

我们知道,if narrow a 变量。

模式遵循了我们的方案能够用来分析某个特定职位可能具有何种价值的可能执行途径。 [......]和提炼类型比所申报的更具体类型的过程称为narrowing

这正是这里所经历的。 字典的理解是,<代码>a实际上是un defined

let a: string | undefined = undefined;
  a;
//^? let a: undefined

选择性链条/<代码>是指-statement作为另一种类型警卫。 它确保<代码>a不是nullun specified。 目前,我们已经考虑了所有可能性。 。 对于这种情况,never-type 正在发挥作用。

变式还从来不以任何种类的警卫加以缩小,永远不会如此。


The reason it works inside a function block is because there s no way to know what s coming in as an argument at compile time. So this time the value really is string | undefined.

let lambda = (value: string | undefined) => {
  value?.toString();
  //^? (parameter) value: string | undefined
};




相关问题
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 ...

热门标签