Home > Software engineering >  Limit generic type (<T>(p: T)=>T, T can be only some specific types)
Limit generic type (<T>(p: T)=>T, T can be only some specific types)

Time:11-15

Any one knows how to make typescript for a function look like this?

const fn = <T>(props: T) => { ...logics which will reuse <T>...}

But T can be only one of boolean or { b: string; }

CodePudding user response:

Use unions if type can only be specific types.

const funSignature = (props: Boolean | String) => {

// ...logics which will reuse <Boolean | String>... }

CodePudding user response:

You could also create your own type.

See below.

type Struct = string | number | boolean;

const fn = <T extends Struct>(props: T) => { ...logics which will reuse <T>...}
  • Related