英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论