Skip to content

Could you explain how does Equal type implementation work? #9100

Answered by sbr61
KnightSlayer asked this question in Q&A
Discussion options

You must be logged in to vote

As a first thought, let's talk about assignability:

type Assignable<X, Y> = X extends Y ? true : false

This tests for assignability of X to Y instead of testing for equality.

So what about mutual assignability? Can we use the following type?

type MutuallyAssignable<X, Y> = X extends Y ? Y extends X ? true : false : false

Actually not. Mutual assignability does not guarantee type equality:

type X1 = { a: string, b?: boolean }
type X2 = { a: string, c?: number }
type X1X2 = MutuallyAssignable<X1, X2> // literal type true

function x1x2(x1: X1, x2: X2) {
    // Mutual assignability:
    x1 = x2; // ok
    x2 = x1; // ok

    // Type inequality:
    x1.b = x2.b; // error: Property 'b' does no…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by KnightSlayer
Comment options

You must be logged in to vote
1 reply
@sbr61
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants