【问题标题】:How to throw a type error during Typescript type checking如何在 Typescript 类型检查期间抛出类型错误
【发布时间】:2020-10-21 22:54:11
【问题描述】:

我有 2 种不应该相交的类型。有没有办法在他们这样做时制作类型检查器标志?理想情况下,我想纯粹在类型世界中执行此操作,而不声明任何冗余变量。

示例:

type A = 1 | 2 // Must be different from B
type B_OK = 3
type B_FAIL = 2 | 3

// What I want (pseudo Typescript)
type AssertDifferent<X,Y> = Extract<X,Y> extends never ? any : fail // Fail if the types intersect

// Expected result (pseudo Typescript)
AssertDifferent<A,B_OK> // TS is happy
AssertDifferent<A,B_FAIL> // Fails type check

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    最好的办法是让条件类型返回真或假,然后尝试将true 分配给结果。像这样:

    type A = 1 | 2 // Must be different from B
    type B_OK = 3
    type B_FAIL = 2 | 3
    
    type AssertTrue<T extends true> = T;
    
    type IsDifferent<X,Y> = Extract<X,Y> extends never ? true : false
    
    type result1 = AssertTrue<IsDifferent<A, B_OK>>; // OK
    type result2 = AssertTrue<IsDifferent<A, B_FAIL>>; // Error
    

    您可以在第二行使用 3.9 版中的新 @ts-expect-error comments 功能来强制始终抛出错误。

    【讨论】:

    • 谢谢!这是一个可行的解决方案;我已经更新了我的答案,包括我想纯粹在类型的世界中这样做,而不声明任何冗余变量。如果那不可能,那么您的建议绝对是有道理的。或者,我想我可以在没有中间类型的情况下执行 const result: Extract&lt;X,Y&gt; = null as never
    • 很公平的@SquattingSlavInTracksuit - 我做了一些修改和编辑,它现在是一个纯粹基于类型的解决方案。
    猜你喜欢
    • 2018-08-24
    • 2018-07-12
    • 2021-05-09
    • 2022-06-21
    • 2018-11-10
    • 2015-05-03
    • 1970-01-01
    • 2021-11-14
    • 2022-10-18
    相关资源
    最近更新 更多