[Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)
typescript in The use Operator
2023-09-14 09:00:46 时间
This lesson introduces the ??
operator which is known as nullish coalescing. The ??
operator produces the value on the right-hand side if (and only if) the value on the left-hand side is null
or undefined
, making it a useful operator for providing fallback values.
We'll contrast the ??
operator with the ||
logical OR operator which produces the value on the right-hand side if the value on the left-hand side is any falsy value (such as null
, undefined
, false
, ""
, 0
, …).
If you want to provide default value, use ?? instead of ||
type SerializationOptions = { formatting?: { indent?: number; }; }; function serializeJSON(value: any, options?: SerializationOptions) { const indent = options?.formatting?.indent ?? 2; return JSON.stringify(value, null, indent); } const user = { name: "Marius Schulz", twitter: "mariusschulz", }; const json = serializeJSON(user, { formatting: { indent: 0, }, }); console.log(json);
相关文章
- [Typescript] Function scope in typescript
- [Typescript] 86. Medium - ToPrimitive
- [TypeScript] AssertType
- [Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)
- [Typescript] Use the Optional Chaining Operator in TypeScript
- [Typescript v4] Tuple Types && Recursive types
- [Tools] Unlock TypeScript's Features in Vanilla JS with @ts-check and JSDoc
- [TypeScript] Query Properties with keyof and Lookup Types in TypeScript
- [TypeScript] Define Custom Type Guard Functions in TypeScript
- [Typescript] Installing Promise Type Definitions Using the lib Built-In Types
- [Typescript] Write clean Type 2 - Reduce the usage in generic slot
- [Typescript] Zod in actions
- [Typescript] 26. Medium - Trim
- [Typescript Challenges] 15. Medium - Get return type of function
- [TypeScript] Work with DOM Elements in TypeScript using Type Assertions
- [Typescript] Installing Promise Type Definitions Using the lib Built-In Types
- [Typescript] Build Method decorators in Typescript
- [Typescript] Sorting arrays in TypeScript
- [TypeScript] Using Exclude and RootDir until File Globs Lands in 2.0.