How to test if two types are exactly the same

后端 未结 3 1429
轮回少年
轮回少年 2020-12-17 01:47

Here is my first attempt: (playground link)

/** Trigger a compiler error when a value is _not_ an exact type. */
declare const exactType: 

        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 02:43

    edit: The most refined version can be found here

    Here's the most robust solution I've found thus far:

    // prettier-ignore
    type Exact = (() => T extends A ? 1 : 0) extends (() => T extends B ? 1 : 0)
        ? (A extends B ? (B extends A ? unknown : never) : never)
        : never
    
    /** Fails when `actual` and `expected` have different types. */
    declare const exactType: (
        actual: Actual & Exact,
        expected: Expected & Exact
    ) => Expected
    

    Thanks to @jcalz for pointing in the right direction!

提交回复
热议问题