条件通用类型的函数被分解成类型的片段
Conditional generic type of function is being broke up into fragments of types
我正在尝试编写通用条件类型。我的尝试是:
type Some<T> = T extends (...args: any[]) => any ? (p: T) => T : T | ((p: T) => T);
当我创建这种类型的变量时
let v: Some<(() => void) | string | boolean>;
它的类型原来是
string | boolean | ((p: string) => string) | ((p: false) => false) | ((p: true) => true) | ((p: () => void) => () => void)
其中甚至 boolean
类型也被分解为 true
和 false
类型,它们的行为是分开的。我实际想要构建的类型是
string | boolean | ((p: string | boolean | (() => void)) => string | boolean | (() => void))
我应该怎么做?
因为条件类型是distributive。我不确定是否可以通过这种方式获得您想要的类型。但是,您可以用不同的方式描述类型,例如:
type Some<T> = Exclude<T, Function> | ((p: T) => T);
至少生成的类型看起来像您期望的类型。 Playground link.
我正在尝试编写通用条件类型。我的尝试是:
type Some<T> = T extends (...args: any[]) => any ? (p: T) => T : T | ((p: T) => T);
当我创建这种类型的变量时
let v: Some<(() => void) | string | boolean>;
它的类型原来是
string | boolean | ((p: string) => string) | ((p: false) => false) | ((p: true) => true) | ((p: () => void) => () => void)
其中甚至 boolean
类型也被分解为 true
和 false
类型,它们的行为是分开的。我实际想要构建的类型是
string | boolean | ((p: string | boolean | (() => void)) => string | boolean | (() => void))
我应该怎么做?
因为条件类型是distributive。我不确定是否可以通过这种方式获得您想要的类型。但是,您可以用不同的方式描述类型,例如:
type Some<T> = Exclude<T, Function> | ((p: T) => T);
至少生成的类型看起来像您期望的类型。 Playground link.