Home > Net >  Unique constraint for TypeScript generics
Unique constraint for TypeScript generics

Time:04-01

The following example should not be considered as a real use case. It should only help to understand the question.

function myFunc<T1 extends string, T2 extends string>(s1: T1, s2: T2): string {
  return "";
}

Is it possible to ensure that T1 !== T2, hence that it is not possible to call myFunc like myFunc("MyValue", "MyValue")?

CodePudding user response:

I think I figured it out.

function myFunc<T1 extends string, T2 extends string>(s1: T1, s2: T2 extends T1 ? never : T2): string {
  return "";
}

CodePudding user response:

No, it's not possible. No, it's not possible.

  • Related