获取子类独有的属性类型

Jac*_*pie 9 typescript

是否可以构造一个 TypeScript 类型来提取特定类所独有的属性名称,而不是从其父类继承?例如,如果我知道父类(Playground Link),这会起作用:

class Parent {
    hello = 'hello'
}

class Child extends Parent {
    world = 'world'
}

type OwnProps<Base, T extends Base> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Parent, Child> // "world"
Run Code Online (Sandbox Code Playgroud)

但是,我想要一种方法来完成相同类型的事情,但没有明确指定基类,如下所示:

type OwnProps<T, Base = T extends ???> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Child> // "world"
Run Code Online (Sandbox Code Playgroud)

这可能吗?我可以使用某种条件魔法来代替???让我infer输入Child类扩展的类型吗?

Val*_*kov 4

不幸的是,这看起来不可能。TypeScript 使用结构类型系统,并且类型不存储有关类层次结构的任何信息,即Child它只是类型{ hello: string, world: string }

您还可以看看其他类似的问题:TypeScript: Get Type of Super Class?