DEV Community

Acid Coder
Acid Coder

Posted on

Typescript Single Import Type Equality Check

background: type equality check

Typescript power users often find themselves in the need of type equality check, and this is the usual way to do it

export type IsEqual<T, U> =
  (<G>() => G extends T ? 1 : 2) extends
  (<G>() => G extends U ? 1 : 2) ? true : false

export const IsTrue = <T extends true>() => {
} 

const a = {a:1,b:2,c:3}
const b = {x:7,y:8,z:9}

IsTrue<IsEqual<typeof a,typeof b>> // error
IsTrue<IsEqual<typeof a,typeof a>> // ok
Enter fullscreen mode Exit fullscreen mode

We always need to import IsEuqal and IsTrue, why can't we just import IsEqual?

This is because IsEqual only return the result, to show the error (the red line), we need IsTrue, IsTrue can be another utility type or function, function is preferrable because we write less code with it.

So can we make life easier, can we combine IsEqual and IsTrue so we only need to import one type/function?

The answer is yes and this is how you do it:

check variable type:

export const IsEqualIsTrue=<T,U>(v:T extends never ? T: T extends never ? T : T, u:U extends never ? U : IsEqual<T,U> extends true ? U : "fail equality check")=>{
  //
}

IsEqualIsTrue(a,b) // error
IsEqualIsTrue(a,a) // ok
Enter fullscreen mode Exit fullscreen mode

I will explain why we need T extends never ? T: T extends never ? T : T in my another post

check type:

export const IsEqualIsTrueType=<T,U>(...args: IsEqual<T,U> extends true ? [] : ["fail equality check"])=>{
  //
}

type A = {a:1,b:2,c:3}
type B = {x:7,y:8,z:9}

IsEqualIsTrueType<A,B>() // error
IsEqualIsTrueType<A,A>() // ok
Enter fullscreen mode Exit fullscreen mode

playground

You still need to write one type and one function, but you only need to export the function.

Enjoy!

Top comments (0)