Reputation: 1373
Is it possible to make two parameters of a function be the exact same dynamically declared type?
function compare(a: string | number, b: typeof a): number {
// ...
}
This currently clones a
's type onto b
, so it's effectively also giving b
the union type of string | number
, so in other words, it's the same as (a: string | number, b: string | number)
. But I'm looking for a way to enforce a strict match, where if a
was a number, b
must also be a number, and vice versa for strings. Examples:
compare(1, 2)
- pass, as expectedcompare('a', 'b')
- pass, as expectedcompare(1, 'b')
- pass, but should failcompare('a', 2)
- pass, but should failUpvotes: 0
Views: 48
Reputation: 250316
You just need a type parameter:
function compare<T extends string | number>(a: T, b: T): number {
return 0;
}
compare(1, 2)
compare('a', 'b')
compare(1, 'b') // err
compare('a', 2) // err
Upvotes: 1
Reputation:
You can use generics to accomplish this:
function compare<T = string | number>(a: T, b: T): number {
// ...
}
Upvotes: 1