You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 15:42:08