Skip to content

Instantly share code, notes, and snippets.

@iegik
Last active December 7, 2023 09:47
Show Gist options
  • Save iegik/dc2c7ec6e5d8c5b3210d7e05c1b99a40 to your computer and use it in GitHub Desktop.
Save iegik/dc2c7ec6e5d8c5b3210d7e05c1b99a40 to your computer and use it in GitHub Desktop.

unknown

unknown | any

;(unknownValue as Function).call(null)

infer

type UnpackArray<T> = T extends (infer R)[] ? R : T
type Foo = UnpackArray<typeof [{foo: 1}]> // { foo: number }

Record

const foo: Record<string, number> = { bar: 1, tar: 2 }

interface

export interface Foo;
export class Foo {
    public bar() {
        // code
    };
}

export interface Bar extends Foo;
export class Bar {
    public override bar() {
        // override code
    };
}

Partial< >

interface Props {
    foo: number;
    bar: string;
}
const obj: Partial<Props> = { foo: 1 }

asserts

console.assert

declare function assert(value: unknown, error: string | Error): asserts value;

asserts ... is ...

function assertIsObject(obj: unknown, errorMessage: string = 'Incorrect object!'): asserts obj is object {
  if(typeof obj !== 'object' || obj === null) throw new Error(errorMessage)
}

function assertIsAddress(address: unknown): asserts address is User['address'] {
  const errorMessage = 'Incorrect address!'
  assertIsObject(address, errorMessage)

  if(
    !('city' in address) ||
    !('state' in address) ||
    !('country' in address) ||
    !('postalCode' in address)
  ) throw new Error(errorMessage)
}

function assertIsUser(user: unknown): asserts user is User {
  const errorMessage = 'Incorrect user!'
  assertIsObject(user, errorMessage)

  if(
    !('id' in user) ||
    !('username' in user) ||
    !('email' in user)
  ) throw new Error(errorMessage)

  assertIsAddress((user as User).address)
}

never

const foo = (value: number): number | never => {
    if(value === 1) return value + 1
    throw new Error('Not alone!')
}

< >

function extend<T extends object, U extends object>(
  value: T,
  extension: U
): asserts value is T & U {
  Object.assign(value, extension);
}

<T, D = T[]>

function indexById<T extends {}, D = Record<T['id'], Partial<T>>>(arr: T[]): D {
  return arr.reduce((acc, { id, ...rest }) => ({ ...acc, [id]: rest }), {});
}
Example ``` interface User { name: string; id: string; } indexById([ { id: '001', name: 'Foo' }, { id: '002', name: 'Bar' }, ]); // { '001': { name: 'Foo'}, '002': { name: 'Bar' } } ```

typeof keyof

const obj = {
    foo: 1,
    bar: '',
}
type Prop = typeof keyof obj;

arrays as types

const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]
// const animals:Animal[] = ['cat', 'dog', 'mouse']

enum

export const enum Say { bark = 'woof woof' } // WARN: with 'const' enum will not be exported as function
const say:Say = 'woof woof' as Say.bark;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment