假设我有类型
type Z = {a: number} | {} | {b: boolean} | {c: string} | ...;
如何获得相同但没有{}
的商品?
type Y = Exclude<Z, {}>;
⇧产生Y = never
的结果,因为所有变体都是{}
的可分配,因此请排除在外。
答案 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 }
答案 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 }