Home > database >  Create Function Type (TypeScript Interface)
Create Function Type (TypeScript Interface)

Time:07-11

I need to make a function type that tells me what the type must be for the second value based on the first value

  type BType = number | string | array
  enum AEnum = { number = "number" , string : "string" , array : "array"} 

  const fc = (a : AEnum , b : BType)=>{ 
   //...
  }
 

What I need is that when a = AEnum.array, then b must be array, or an error should be shown

How can I make something like this ??

CodePudding user response:

Just overload the function !

type BType = number | string | []
enum AEnum { number = "number", string = "string", array = "array" }

function foo(a: AEnum.number, b: number): unknown;
function foo(a: AEnum.string, b: string): unknown;
function foo(a: AEnum.array, b: []): unknown;
function foo(a: AEnum, b: BType): unknown {
    return void;
}

Playground

  • Related