Skip to content

Latest commit

 

History

History
90 lines (67 loc) · 3.76 KB

in-domain-null.md

File metadata and controls

90 lines (67 loc) · 3.76 KB

Item 36: Use a Distinct Type for Special Values

Things to Remember

  • Avoid special values that are assignable to regular values in a type. They will reduce TypeScript's ability to find bugs in your code.
  • Prefer null or undefined as a special value instead of 0, -1, or "".
  • Consider using a tagged union rather than null or undefined if the meaning of those values isn't clear.

Code Samples

function splitAround<T>(vals: readonly T[], val: T): [T[], T[]] {
  const index = vals.indexOf(val);
  return [vals.slice(0, index), vals.slice(index+1)];
}

💻 playground


function safeIndexOf<T>(vals: readonly T[], val: T): number | null {
  const index = vals.indexOf(val);
  return index === -1 ? null : index;
}

💻 playground


function splitAround<T>(vals: readonly T[], val: T): [T[], T[]] {
  const index = safeIndexOf(vals, val);
  return [vals.slice(0, index), vals.slice(index+1)];
  //                    ~~~~~              ~~~~~ 'index' is possibly 'null'
}

💻 playground


function splitAround<T>(vals: readonly T[], val: T): [T[], T[]] {
  const index = safeIndexOf(vals, val);
  if (index === null) {
    return [[...vals], []];
  }
  return [vals.slice(0, index), vals.slice(index+1)];  // ok
}

💻 playground


interface Product {
  title: string;
  priceDollars: number;
}

💻 playground


interface Product {
  title: string;
  /** Price of the product in dollars, or -1 if price is unknown */
  priceDollars: number;
}

💻 playground


// @strictNullChecks: false
const truck: Product = {
  title: 'Tesla Cybertruck',
  priceDollars: null,  // ok
};

💻 playground