SILENT
SILENT

Reputation: 4268

Testing expected typescript's type

I'm trying to statically type check some types for a library.

I'm using

export type Expect<T extends E, E> = T extends E ? true : false;

and its working for most tests. However, if I try testing the following:

type TypeA = {
    prop1: {
        str: string;
    };
    prop2?: {
        str: string;
    };
}

type TypeB = {
    prop1: {
        str: string;
    };
    prop2?: {
        str?: string; // different from TypeA
    }
}

type _Check = Expect<TypeA, TypeB>; // No error why?

Playground

TypeA equals TypeB (ie no error is reported).

  1. Why is there no error when comparing TypeA with TypeB
  2. How to deep check that the types are equal?

Upvotes: 0

Views: 119

Answers (1)

Acid Coder
Acid Coder

Reputation: 2747

export type Expect<T, E> = T extends E ? E extends T? true : false: false

type TypeA = {
    prop1: {
        str: string;
    };
    prop2?: {
        str: string;
    };
}

type TypeB = {
    prop1: {
        str: string;
    };
    prop2?: {
        str?: string; // different from TypeA
    }
}

const isTrue=<T extends true>()=>{}

isTrue<Expect<TypeA, TypeB>>() // expect error
isTrue<Expect<TypeA, TypeA>>() // ok

enter image description here playground

in your code TypeA extends TypeB but TypeB doesn't extends TypeA, that is why you don't get the error when compare TypeA to TypeB, but you will get error if you compare TypeB to TypeA

Upvotes: 1

Related Questions