简体   繁体   中英

Create Function Type (TypeScript Interface)

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 ??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM