Posts

Showing posts from August, 2022

typescript notes (typeof, keyof, ReturnType, Parameters, Extract)

  typeof extract a type from runtime code, typeof "make a type of it" (i.e. from it) e.g.   typeof "Hello world"  => string only legal on variable names can be used with functions or any other expressions aside: typeof vs keyof: keyof takes a type and creates a string/number union of it's keys. So keyof creates a new type from a type ....whereas typeof creates a type from an expression. good post Given a function: const myFunc = (name: string) => {   return `hello ${name}`;    }; type the function into MyFunc type MyFunc =   typeof myFunc; type a function return type (using built in ReturnType ) type MyFuncReturn = ReturnType<typeof myFunc>;  // string When the function changes, the types change! You can also type the parameters using utility type  Parameters      type MyFuncParams = Parameters<typeof myFunc>;  // string but Parameters will return a tuple (array), so you could index result like so:  MyFuncParams[0] i.e. can use indexes on tupl