Home > Software design >  How to do type check in a way that two arguments have different values in TypeScritp?
How to do type check in a way that two arguments have different values in TypeScritp?

Time:11-20

Consider the following code:

type Country = "usa" | "uk" | "canada";
function match({c1, c2}:{c1:Country, c2: Exclude<Country, c2>}){} //This is error
match('usa', 'usa'); //I want this to be a error
match('uk', 'usa'); //and this be ok

I want to force arguments c1 and c2 have different values when called.

CodePudding user response:

You can use generics as follows:

function match<C extends Country>(c1: C, c2: Exclude<Country, C>){}

I will probably only work properly if the arguments are literal strings, though, so it might not be easy to use if you are planning to use something else (like variables) for the arguments.

  • Related