Quangdao Nguyen
Quangdao Nguyen

Reputation: 1373

Can a param be set as the "same type" as another param in Typescript?

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:

Upvotes: 0

Views: 48

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Playground Link

Upvotes: 1

user12251171
user12251171

Reputation:

You can use generics to accomplish this:

function compare<T = string | number>(a: T, b: T): number {
  // ...
}

Playground link.

Upvotes: 1

Related Questions