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

TypeScript中如何访问对象嵌套字段自动生成组件属性校验类型

报错核心原因
  • 类型拓宽问题:你用let声明的customComponentProps会被TS自动拓宽类型,内部的type: String会被识别为通用的CleanPropType联合类型,丢失了具体是String构造器的信息,导致后续无法准确推导类型。
  • 工具类型使用错误:ReturnType适用于普通函数的返回值推导,而String/Boolean这些是原生构造器,需要用InstanceType来获取其对应的实例类型。同时直接访问T[name].type的写法,在联合类型未收窄的场景下TS无法识别。
  • 拼写错误:测试用例中引用的custromComponent是拼写错误,正确应为customComponent,也会引发报错。
修复方案
  1. 固化配置对象类型:将customComponentProps改为const声明,同时添加as const修饰,锁定内部每个字段的type对应的具体构造器类型,避免类型拓宽。
  2. 替换工具类型:将ReturnType替换为InstanceType,适配原生构造器的实例类型推导。
  3. 修正索引访问写法:将映射类型内的属性访问调整为T[Name]['type']的索引访问写法,符合TS类型语法规范。
  4. 修正类型名拼写错误。
最终可运行代码
type CleanPropType = typeof Array | typeof Object | typeof Function | typeof Boolean | typeof String;

type Prop = {
    type: CleanPropType,
    default?: any
}

type Props = Record<string, Prop>

// 加as const固化类型,避免类型拓宽
const customComponentProps = {
    name: {
        type: String
    }
} as const

// 改写生成器类型,用InstanceType获取构造器对应的实例类型
type CustomComponentGenerator<T extends Props> = {
    [Name in keyof T]: InstanceType<T[Name]['type']>
}

// 生成最终的组件属性类型
type CustomComponent = Partial<CustomComponentGenerator<typeof customComponentProps>>;

// 符合预期无报错
let userComponentProps : CustomComponent = {
    name: 'ComponentNameString',
}

// 预期两处报错:name类型不匹配、存在未定义的otherField字段
let userComponentProps2 : CustomComponent = {
    name: false,
    otherField: 'str'
}

内容的提问来源于stack exchange,提问作者Artem Skibin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:54:07