Typescript "Object is possibly 'undefined'" for object literal

huangapple go评论61阅读模式
英文:

Typescript "Object is possibly 'undefined'" for object literal

问题

In the browser console, I can do this in JavaScript just fine:

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid).rssi;

Result: 54

When I attempt the exact same thing in my TypeScript app, TypeScript says "Object is possibly 'undefined'":

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid).rssi;

What do I need to change to get this to work?

英文:

In the browser console I can do this in js just fine:

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid).rssi

54

When I attempt the exact same thing in my Typescript app, Typescript says "Object is possibly 'undefined'":

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid).rssi;

What do I need to change to get this to work?

答案1

得分: 1

在闭合的圆括号后添加问号,如果没有与条件匹配的对象,find 可能返回未定义,尽管在你的示例中这种情况永远不会发生,但仍然需要通过可选链接来检查它。

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid)?.rssi;

英文:

Add the question mark after the closing round bracket, find can return undefined if there is no object that matches the condition, and although in your example this will never happen it is still something you need to check by doing optional chaining.

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid)?.rssi;

答案2

得分: 1

The find method may not find what you're looking for and may be possibly undefined. You can use '?'.

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid)?.rssi;
英文:

The find method may not find what your looking for and be possibly undefined. You can use '?'.

[{ssid: 'Test Network 1', rssi: 54},{ssid: 'Test Network 2', rssi: 60}].find((rec) => 'Test Network 1' === rec.ssid)?.rssi;

huangapple
  • 本文由 发表于 2023年5月25日 12:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定