Skip to content

Instantly share code, notes, and snippets.

@roalcantara
Last active September 4, 2020 06:55
Show Gist options
  • Select an option

  • Save roalcantara/d9025aa894561f7731f31f9b1b6a7587 to your computer and use it in GitHub Desktop.

Select an option

Save roalcantara/d9025aa894561f7731f31f9b1b6a7587 to your computer and use it in GitHub Desktop.
Typescript 4.0: Short-Circuiting Assignment Operators
// Then
const append = (values: string[], value: string) => {
(values ?? (values = [])).push(value)
return values
}
// Now
const append = (values: string[], value: string) => {
(values ??= []).push(value)
return values
}
source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#short-circuiting-assignment-operators
// Then
const assign = <T>(a: T, b: T) => {
if (!a) {
a = b
}
return a
}
// Now
const assign = <T>(a: T, b: T) => {
a ||= b
return a
}
source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#short-circuiting-assignment-operators
// Then
export const assign2 = (obj: { prop: string }, foo: () => string) => {
if (!obj.prop) {
obj.prop = foo()
}
return obj
}
// Now
export const assign2 = (obj: { prop: string }, foo: () => string) => {
obj.prop ||= foo()
return obj
}
source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#short-circuiting-assignment-operators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment