Types
- https://www.zhenghao.io/posts/type-programming (opens in a new tab)
- https://www.zhenghao.io/posts/type-functions (opens in a new tab)
- https://learntypescript.dev/07/l7-assertion-signature (opens in a new tab)
Type narrowing
type guard
function isTypeName(paramName: WideTypeName): paramName is NarrowTypeName {
// some check
return boolean_result_of_check;
}type assertion
export default function invariant(value: boolean, message?: string): asserts value;
export default function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
// impl
export default function invariant(value: unknown, message?: string) {
if (value === false || value === null || typeof value === 'undefined') {
throw new InvariantError(message);
}
}Function overload
type F = ((input: string) => string) & ((input: number) => number)
const switchIt_intersection: F = (input) => {
if (typeof input === 'string') {
return Number(input)
} else {
return String(input)
}
}
const num = switchIt_intersection(1) // ✅ has the string type
const str = switchIt_intersection('1') // ✅ has the number type
The type hierarchy tree
- upcast types is safe (e.g.
let foo: unknown = "string") - downcast types is unsafe (e.g.
let unknownVar: unknown, let foo: string = unknown) anyis an exception (it can both up/down cast types, i.e. opt-out of type safety)
(`any`, `unknown`) -> (`string`, `number`, `boolean` etc) -> (`undefined`, `void`)
supertype -> subtypeTypes exist to ensure that the data is correct at runtime https://www.zhenghao.io/posts/type-hierarchy-tree (opens in a new tab)
