如何在Typescript类型检查期间抛出类型错误

3

我有两种类型,它们永远不应该相交。是否有一种方法可以使类型检查器在它们相交时标记出来?理想情况下,我希望在类型世界中纯粹地实现这一点,而不声明任何多余的变量。

示例:

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

1个回答

3

最好的方法是让你的条件类型返回true或false,然后尝试将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注释,以确保错误始终抛出。

谢谢!那是一个可行的解决方案;我已经更新了我的答案,包括我想在类型世界中纯粹地完成这个任务,而不声明任何多余的变量。如果不可能,你所建议的绝对有道理。或者,我猜我可以只做 const result: Extract<X,Y> = null as never 而不需要中间类型。 - SquattingSlavInTracksuit
好的,@SquattingSlavInTracksuit,我做了一些调整并编辑了它,现在它是一个纯类型解决方案。 - Tim Perry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接