TIL about the Standard Schema! It’s an effort to standardize the interface of TypeScript validation libraries.
To pull directly from the docs, The goal is to make it easier for ecosystem tools to accept user-defined type validators, without needing to write custom logic or adapters for each supported library.
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"