如何提取TypeScript子类的自有属性生成对应对象字面量类型
问题原因
你当前的泛型直接遍历构造函数类型的key,拿到的是构造函数自身的静态属性,而非类实例的成员属性,因此无法正确提取Signup的实例字段。
修正方案
调整ObjectProps的泛型定义,使用TS内置工具类InstanceType提取构造函数对应的实例类型,再做属性过滤即可:
type Constructor = new (...args: any[]) => {} // 修正后的泛型定义 type ObjectProps<T extends Constructor, V extends Constructor | undefined = undefined> = V extends Constructor ? Omit<InstanceType<T>, keyof InstanceType<V>> : InstanceType<T> class Joke { anythingNotInOriginal: boolean = true } class Signup extends Joke { email: string = '' username: string = '' password: string = '' } type x = ObjectProps<typeof Signup, typeof Joke> // 此时x的类型就是你需要的 { email: string, username: string, password: string } const v: x = { username: 1 // 这里会直接抛出类型错误,符合预期 }
内容的提问来源于stack exchange,提问作者ThomasReggi
相关产品推荐
相关产品推荐

