2

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

2
  • Please provide a self-contained minimal reproducible example that clearly demonstrates the issue you are facing. Ideally I could paste such code into a standalone IDE and immediately get to work solving the problem without first needing to re-create it. So there should be no pseudocode, typos, unrelated errors, or undeclared types or values. Commented Jul 10, 2022 at 15:56
  • 1
    @jcalz I think the question is actually quite clear Commented Jul 10, 2022 at 15:58

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.