English 中文(简体)
StypeScript 无法推断类型,在符合逻辑或逻辑的 或
原标题:TypeScript failing to infer type is not undefined after type guard with logical or
  • 时间:2024-07-24 12:18:35
  •  标签:
  • typescript
In the code below, in the else block, it is clear that b cannot be undefined (a||b is truthy and a is falsy so b must be truthy). Why does Typescript produce the error b is possibly undefined , and how can I avoid this error? function test(a: string | undefined, b: string | undefined) { if (a || b) { if (a) { const x = a.length } else { const y = b.length } } }
问题回答
You can debug it like this: function test(a: string | undefined, b: string | undefined) { type A1 = typeof a; // string | undefined type B1 = typeof b; // string | undefined if (a || b) { type A2 = typeof a; // string | undefined type B2 = typeof b; // string | undefined if (a) { type A3 = typeof a; // string type B3 = typeof b; // string | undefined const x = a.length } else { type A4 = typeof a; // string | undefined type B4 = typeof b; // string | undefined const y = b.length } } } Basically, (a || b) is not able to narrow down the types. The conditional flow analysis looks for for !== undefined and !== null checks, you should re-write it as follows: function test(a: string | undefined, b: string | undefined) { if (a !== undefined ) { const x = a.length; // number } else if(b !== undefined){ const y = b.length; // number } }




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

热门标签