-
用于空值检查(
'undefined'andnull)let account={id: 1} let deparmentid=account?.id console.log(deparmentid) // return id if an account is not null or undefined, else return undefined -
用于定义可选属性(optional properties),Much of the time, we’ll find ourselves dealing with objects that might have a property set. In those cases, we can mark those properties as optional by adding a question mark (?) to the end of their names.
interface PaintOptions { shape: Shape; xPos?: number; yPos?: number; } function paintShape(opts: PaintOptions) { // ... } const shape = getShape(); paintShape({ shape }); paintShape({ shape, xPos: 100 }); paintShape({ shape, yPos: 100 }); paintShape({ shape, xPos: 100, yPos: 100 });We can also read from those properties - but when we do under
strictNullChecks, TypeScript will tell us they’re potentially undefined.
TypeScript Question Mark/问号 (?)
最新推荐文章于 2024-11-04 16:09:44 发布
本文介绍了如何利用JavaScript中的可选链操作符('?')来简化空值检查,并展示了如何将其应用到TypeScript中定义可选属性,使得代码更加简洁且易于维护。
591

被折叠的 条评论
为什么被折叠?



