Types

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

(`any`, `unknown`) -> (`string`, `number`, `boolean` etc) -> (`undefined`, `void`)

supertype -> subtype

Types exist to ensure that the data is correct at runtime https://www.zhenghao.io/posts/type-hierarchy-tree (opens in a new tab)