Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript how to test if two generics are equivalent? [duplicate]

What I wish to accomplish is something along the line of:

type AType<T, U> = (T is Equal U) ? T : [T, U]

[EDIT] base on a comment let me rephrase by a practical example:
Let's assume T is a UInt8Array the equality is if U is also a UInt8Array.
The equivalence is defined by the same type.

[EDIT 2] Based on @daniel-hilgarth answers
It doesn't work as T extends U in practical usage (see below) if we assume T and U are numbers, T will be casted to the instance of the number passed, as in T won't be a number but T will be a 2 that extends the type number. So if U is 3 it won't extend 2

Sorry if it's unclear, please check implementation below

type AType<T, U> = T extends U ? U extends T ? T : [T, U] : [T, U]

const fn = <T extends string | number, U extends string | number>(
  x: T,
  y: U,
): AType<T, U> => {
  throw new Error ('Yet to implement !')
}

const a = fn (2, 2)    // correct number
const b = fn (2, 's')  // correct [number, string]

but

const c = fn (2, 3)    // incorrect [number, number]

What i need is not:

  • if T extends U

But:

  • if T extends whatever U extends

I hope it clarifies the question.

Can it be done?

like image 820
zedryas Avatar asked Nov 02 '25 12:11

zedryas


1 Answers

Currently, for conditional types there is only one question that you can ask: extends. There is no equal, but we can simulate it by using two checks:

type AType<T, U> = T extends U ? U extends T ? T : [T, U] : [T, U]

First, we check if T extends U. If so, we check if U extends T. Both conditions can only be true at the same time if T and U are of the exact same type, so we return T.

This works correctly in Typescript 3.2:

proof

(link)

Also, worth reading for an understanding of Conditional Types in general: https://koerbitz.me/posts/a-look-at-typescripts-conditional-types.html

like image 119
Daniel Hilgarth Avatar answered Nov 04 '25 10:11

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!