在TypeScript中获取仅包含类自有属性的类型
解决方案
你可以通过两种方式实现类型的自动同步,无需手动维护属性列表:
方案一:利用TypeScript自动推断(最简便)
直接使用typeof instanceSpread作为函数参数的类型,TypeScript会自动捕获展开后对象的所有属性类型,包括TestClass的实例属性和新增的anotherProperty。当TestClass后续新增属性时,instanceSpread的类型会自动同步更新。
示例代码:
class TestClass { readonly firstProperty: number; readonly secondProperty: string; // 后续新增属性时,类型会自动同步 readonly thirdProperty: boolean; constructor() { this.firstProperty = 5; this.secondProperty = 'test'; this.thirdProperty = true; } logProperties() { console.log(this.firstProperty); console.log(this.secondProperty); } } const instance = new TestClass(), instanceSpread = { ...instance, anotherProperty: 'hello' }; // 直接用typeof instanceSpread声明参数类型 function processSpread(spread: typeof instanceSpread) { console.log(spread.firstProperty); console.log(spread.anotherProperty); console.log(spread.thirdProperty); // 新增属性自动被识别 } processSpread(instanceSpread);
方案二:自定义工具类型提取非方法属性(适合复用场景)
如果需要在多个函数中复用这个类型,可以定义一个工具类型,专门过滤掉类中的方法属性,只保留实例属性,再与新增属性的类型交叉。这样后续TestClass新增非方法属性时,工具类型会自动纳入新属性。
示例代码:
// 工具类型:提取类实例的非方法属性 type InstanceNonMethodProperties<T> = { [K in keyof T as T[K] extends Function ? never : K]: T[K] }; class TestClass { readonly firstProperty: number; readonly secondProperty: string; constructor() { this.firstProperty = 5; this.secondProperty = 'test'; } logProperties() { console.log(this.firstProperty); console.log(this.secondProperty); } } const instance = new TestClass(), instanceSpread = { ...instance, anotherProperty: 'hello' }; // 组合工具类型与新增属性类型 type InstanceSpreadType = InstanceNonMethodProperties<TestClass> & { anotherProperty: string }; function processSpread(spread: InstanceSpreadType) { console.log(spread.firstProperty); console.log(spread.anotherProperty); } processSpread(instanceSpread);
内容的提问来源于stack exchange,提问作者Awacate
相关产品推荐
相关产品推荐

