TIL about how one can use satisfies
in typescript, without satisfy
at all!
// taken right from Kent's blog
type OperationFn = (left: number, right: number) => number
// this is a restriction on the operations object
// but with satisfies, I leave myself room to add more operations and don't need to manage another type
const operations = {
'+': (left, right) => left + right,
'-': (left, right) => left - right,
'*': (left, right) => left * right,
'/': (left, right) => left / right,
} satisfies Record<string, OperationFn>
TIL there’s a tool that can help you find out if your types are wrong for your library!
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"