Skip to content

Instantly share code, notes, and snippets.

@LarsBuur
Forked from wmakeev/NullableKeys.md
Created January 12, 2021 09:57
Show Gist options
  • Select an option

  • Save LarsBuur/4a59281a4213d91bc1b7913cfcef0adf to your computer and use it in GitHub Desktop.

Select an option

Save LarsBuur/4a59281a4213d91bc1b7913cfcef0adf to your computer and use it in GitHub Desktop.
[TypeScript Tips] #typescript #tips #cheatsheet

Function wrapper

function spreadsheetErrorHandler<T extends (...args: any[]) => any>(
  func: T
): T {
  return <T>function (...args: any[]) {
    try {
      return func(...args)
    } catch (err) {
      if (
        err instanceof SpreadsheetHelper.SpreadsheetHelperError &&
        err.range
      ) {
        throw new CellValueError(err.message, err.range)
      }

      throw err
    }
  }
}

Select keys by type

type StringOrNumber = string | number

interface A {
  a: string
  b: number
  c: string[]
  d: Date
}

type SelectKeys<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

type keys = SelectKeys<A, StringOrNumber> // type keys = "a" | "b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment