0

I have a function with one generic parameter, but with two function parameters. When I use "String Literal Type" the two function parameter can be have differt values:

function func2<T extends 'A' | 'B'>(x: T, y: T): void { }

func2('A', 'A'); // OK
func2('A', 'B'); // OK, why?
func2('A', 'C'); // ERR

But I need that x and y are the same, like the example with Classes:

class A {  public a;}
class B {  public b;}
class C {  public c;}

function func1<T extends A | B>(x: T, y: T): void { }

func1(new A(), new A()); // OK
func1(new A(), new B()); // ERR
func1(new A(), new C()); // ERR

Is there any way that x and y have the same value with "String Literal Type"?

3
  • 1
    The parameters both match the constraint, and the order is irrelevant so the appropriate inference is taking place, however you can write func2<T extends 'A' | 'B', U extends T>(x: T, y: U). That makes the second constraint depend on the first Commented Apr 11, 2020 at 16:38
  • Thanks Aluan Haddad that solves my problem. I am new to Stackoverflow, how can I mark your answer as the solution? Commented Apr 12, 2020 at 18:52
  • Oh, this isn't an answer, it's a comment. I'll add an answer later Commented Apr 12, 2020 at 19:02

1 Answer 1

1

Aluan Haddad's comment solves the problem:

The parameters both match the constraint, and the order is irrelevant so the appropriate inference is taking place, however you can write func2(x: T, y: U). That makes the second constraint depend on the first

Now both parameters can only have the same value:

function func2<T extends 'A' | 'B', U extends T>(x: T, y: U): void { }

func2('A', 'A'); // OK
func2('A', 'B'); // ERR
func2('A', 'C'); // ERR
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.