Published on

Typescript

Authors
  • avatar
    Name
    Timothy Blanks

Define a type for an unknown JS library

declare var UnknownType: any

retry

Wait for an element then continue with code

const waitForButton = () => {
  const btn = findButtonByText('button')

  // no button the pause and retry
  if (!btn) {
    setTimeout(waitForButton, 1000)
    return false
  }

  // Condition met
  // ...
  // Do the work here.

  return true
}

Set up fake type for external JS code

declare var ModuleName: any

Union type with options, when any just won't do, will allow intellisense to work

export type someType = 'option1' | 'option2' | (string & { fromT?: any })

Union type from array of objects

const list = [
  { name: 'a', value: 423 },
  { name: 'b', value: 423 },
  { name: 'c', value: 423 },
  { name: 'another', value: 423 },
] as const

type nameTypes = typeof list[number]['name']
//   ^? nameTypes = "a" | "b" | "c" | "another"

Sleep or Wait

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))