Typescript Generic Function

Posted by fsanren on November 24, 2022

Typescript Generic Function

function makePair<
F extends number | string,
S extends boolean | F
>()
  • Generic function only able to pass number, string

function makeState<S extends number | string>()

  • Generic function default type as number

function makeState<S extends number | string = number>()

  • Generic function with multiple type parameters ```typescript // makeState() has 1 type parameter function makeState() // makePair() has 2 type parameters function makePair<F, S>()

// The second parameter S must be either // boolean or whatever was specified for F function makePair< F extends number | string, S extends boolean | F >()


### Generic classes
```ts
function makeState<S>() {
  let state: S
  function getState() {
    return state
  }
  function setState(x: S) {
    state = x
  }
  return { getState, setState }
}

// Pass a type parameter on initialization
const numState = new State<number>()

Common Used Abbreviation

  • T (for “T”ype)
  • E (for “E”lement)
  • K (for “K”ey)
  • V (for “V”alue)
  • S (for “S”tate)