Taran_logo_black
TILBLOGABOUT

Today I learned about...
typescript

Back to all tags

Want to have some type hinting for a union but allow any string value?!

Use this hack bruh:

type color = 'red' | 'blue' | 'green' | (string & {})

function getColor(c: color) {
  console.log(c)
}

getColor('red') // editor will code complete this for you
getColor('yolo') // this works!

TypeScript has a handy utility type to extract types from a union type 🤭.

type MyUnion = 'Hello' | 'Mom' | 'I' | 'Love' | 'You'
type WithoutMom = Extract<MyUnion, 'Mom'>
// the above will be the type "Hello" | "I" | "Love" | "You"