Photo by Laurin Steffens, https://unsplash.com/de/fotos/eine-gruppe-weisser-und-orangefarbener-objekte-IVGZ6NsmyBI

Table of Contents

Conditional (Ternary) Operator

condition ? exprIfTrue : exprIfFalse

Depending on whether its first operand is truthy or falsy, returns either its second or third operand.

console.log(true      ? 'then' : 'else');  // then
console.log(false     ? 'then' : 'else');  // else
console.log(null      ? 'then' : 'else');  // else
console.log(undefined ? 'then' : 'else');  // else
console.log(''        ? 'then' : 'else');  // else

MDN: Conditional (ternary) operator

Nullish Coalescing Operator

leftExpr ?? rightExpr

Returns its right side if its left side is null or undefined. Otherwise, returns its left side.

console.log('left'    ?? 'right');  // left
console.log(null      ?? 'right');  // right
console.log(undefined ?? 'right');  // right
console.log(''        ?? 'right');  // ''

The ?? operator is stricter than the logical OR operator ||, which doesn’t only check for null / undefined, but also for “falsy” values (such as empty strings, or 0).

MDN: Nullish coalescing operator

Optional Chaining

obj?.prop

Returns undefined when trying to access a property of an object that is null or undefined.

const nullObject = null;
const undefinedObject = undefined;
const someObject = { someProperty: 42 };

console.log(nullObject?.someProperty);       // undefined
console.log(undefinedObject?.someProperty);  // undefined
console.log(someObject?.someProperty);       // 42

MDN: Optional chaining (?.)

Optional Parameters (TypeScript)

param?: type

Shorthand for adding ‘undefined’ to the parameter’s type.

function foo(maybeUndefined?: string) {
  console.log(maybeUndefined);
}

foo('test');     // test
foo(undefined);  // undefined
foo();           // undefined

TypeScript: Optional Parameters

Optional Properties (TypeScript)

property?: type;

Shorthand for adding ‘undefined’ to the property’s type.

interface Foo {  // analogous with 'type'
  a:  number;
  b?: number;
}

const full:  Foo = { a: 1, b: 2 };
const part1: Foo = { a: 1 };
const part2: Foo = { a: 1, b: undefined };

TypeScript: Optional Properties

Conditional Types (TypeScript)

SomeType extends OtherType ? TrueType : FalseType;

Depending on whether the ‘extends’ clause is true or false, this resolves to either ‘TrueType’ or ‘FalseType’.

When combined with generics, this allows for the definition of functions whose return type depends on a parameter type (as an alternative to using function overloads).

interface NumberLabel {
  label: number;
}

interface StringLabel {
  label: string;
}

type NumberOrStringLabel<T extends number | string> =
  T extends number ? NumberLabel : StringLabel;

function createLabel<T extends number | string>(p: T): NumberOrStringLabel<T> {
  return { label: p } as NumberOrStringLabel<T>;
}

const numberLabel = createLabel(42);
const stringLabel = createLabel('foo');

TypeScript: Conditional Types