是否有一种方法可以直接从Typescript的联合类型中排除类型?



例如,我想从给定的联合类型中排除函数类型。

type T = number | string | VoidFunction;  // a GIVEN type
type R = ExcludeType<T, VoidFunction>;  // number | string

我发现我可以通过添加一个工具功能来实现:

type T = number | string | VoidFunction;  // a GIVEN type
function f(v: T) {
if (v instanceof Function) return undefined;
return v;
}
type R = typeof f;  // number | string

但是我认为它很复杂,不可扩展,而且我不能在'.d中使用它。

有更好的方法吗?

这只是Exclude:

type R = Exclude<T, VoidFunction>;  // number | string

游乐场


Exclude<Type, ExcludedUnion>

通过从Type中排除所有可赋值给ExcludedUnion的联合成员来构造一个类型。

最新更新