TypeScript泛型类使用报错:AttributeType不存在属性bar怎么办?
问题原因
你的代码写法存在问题,核心是混淆了TypeScript泛型的默认类型参数和泛型约束两个独立特性:
- 你写的
AttributeType = { bar: string }仅表示:当实例化类时如果不手动传入泛型类型,AttributeType会默认使用{ bar: string }这个类型。但语法本身没有对AttributeType的可能取值做任何限制,你完全可以传入任意其他类型实例化类,比如new Some<{ foo: number }>()、甚至new Some<string>(),这种情况下attrs上不存在bar属性,TypeScript出于类型安全考虑,会直接抛出属性不存在的错误。 - TypeScript不会因为你给泛型设置了默认值,就默认所有可能的泛型取值都符合默认值的结构。
修复方案
给泛型参数加上明确的类型约束,强制所有传入的AttributeType都必须包含bar: string结构,同时保留原有的默认类型即可:
class Some<AttributeType extends { bar: string } = { bar: string }> { foo(attrs: AttributeType) { if (attrs.bar) { console.log(attrs.bar) } } }
修复后两种使用场景都能正常通过类型校验:
- 不传入泛型参数,直接使用默认类型实例化:
new Some(),调用foo时只需要传入符合{bar: string}结构的参数 - 传入自定义的扩展类型实例化,只要自定义类型满足包含
bar: string的约束即可,比如:
interface CustomAttr { bar: string id: number } const instance = new Some<CustomAttr>() instance.foo({ bar: "test", id: 1 }) // 校验通过
内容的提问来源于stack exchange,提问作者Lordent
相关产品推荐
相关产品推荐

