有一个建议的特性允许您告诉编译器
T
是许多类型之一,而不是它们的联合。这个
issue
在讨论中标记为,因此可能添加一个+1。
同时,如果
T
是使用条件类型的联合:
type Any = "A" | "B"
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
type NoUnion<T, TError> = [T] extends [UnionToIntersection<T>] ? {} : TError
type d = NoUnion<Any, "">
const fn = <T extends Any>(arg: T[] & NoUnion<T, "Must be A or B not a union">) => { }
fn(null as "A"[])
fn(null as "B"[])
fn(null as ("A" | "B")[]) //error Type 'Any[]' is not assignable to type '"Must be A or B not a union"'