如何从其他类型中排除{}?

时间:2020-09-13 03:53:22

标签: typescript

假设我有类型

type Z = {a: number} | {} | {b: boolean} | {c: string} | ...;

如何获得相同但没有{}的商品?

type Y = Exclude<Z, {}>;

⇧产生Y = never的结果,因为所有变体都是{}可分配,因此请排除在外。

2 个答案:

答案 0 :(得分:2)

您可以定义自己的类似Exclude的类型函数,例如ExcludeSupertypes<T, U>,该函数将T拆分为其联合成员,并排除所有属于此类的 supertypes 成员。 U代替U子类型

type ExcludeSupertypes<T, U> = T extends any ? U extends T ? never : T : never;

您可以在Z上进行此操作:

type Y = ExcludeSupertypes<Z, {}>
// type Y = { a: number } | { b: boolean } | { c: string }

Playground link to code

答案 1 :(得分:1)

jcalz的答案很棒,据我了解,我认为也许有一种基于jcalz的方法,可以排除完全相同的类型。

cv2.fillPoly(mask, pts, 255) cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-k8sx3e60\opencv\modules\imgproc\src\drawing.cpp:2395: error: (-215:Assertion failed) p.checkVector(2, CV_32S) >= 0 in function 'cv::fillPoly'

这可以根据需要进行操作:

type ExcludeExact<T, U> = T extends any ? U extends T ? (T extends U ? never : T) : T : never;

并以这种方式工作:

type Y = ExcludeExact<Z, {}>
// type Y = { a: number } | { b: boolean } | { c: string }