【发布时间】:2019-11-21 23:11:51
【问题描述】:
当(此属性的)泛型参数为never 时,我需要一个从指定类型中排除泛型属性的泛型类型。为此,我使用了Omit 和条件类型。例如,当泛型参数设置为 number 时,它的行为与预期一样,但当泛型类型设置为 never 时,类型解析为 never 而不是排除指定的属性 (Playground):
type BaseType<T> = {
prop1: string;
genProp1: T;
};
type Excluded<T> = T extends never ? Omit<BaseType<T>, "genProp1"> : BaseType<T>;
const obj1: Excluded<number> = {
genProp1: 5,
prop1: "something, something"
};
//obj2 is never
const obj2: Excluded<never> = {
prop1: "dark side" //error: Type 'string' is not assignable to type 'never'
};
为什么要这样做,我怎样才能让它返回正确的类型 ({ prop1: string })?
编辑: 比较 null 而不是 never 解决了这个问题。当我使用never 时,我仍然想知道发生了什么。
【问题讨论】:
标签: typescript generics conditional-types