-
用于空值检查(
'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.