TypeScript定义对象类型时出现string类型参数无索引签名报错
报错根因
你遇到的类型报错是因为property参数的类型为宽泛的string,但topBarType仅支持height、font-size、iconWidth、iconHeight四个固定值作为索引,TypeScript无法确认你传入的字符串一定是topBarType的合法键,因此触发了类型校验拦截。
修复步骤
- 收窄
property参数的类型,使用keyof操作符直接关联topBarType的键集合,代替原本的string类型,从根源上保证传入的property一定是合法索引 - 可选优化:将
theme的类型替换为Record<variantTypes, topBarType>,可以进一步强化variant参数的类型校验,避免出现非法的variant取值 - 注意:你当前定义的
variant类型为非空的variantTypes联合类型,if (!variant)的判断逻辑永远不会触发,如果确实存在variant为空的场景,需要将参数类型调整为variant: variantTypes | undefined
完整修复后代码
type topBarType = { height: string; "font-size": string; iconWidth: string; iconHeight: string; }; type variantTypes = 'sm'|'md'|'lg'; // 仅修改了property的类型为keyof topBarType export function topBarTheme(variant: variantTypes | undefined, property: keyof topBarType): string { // 可选优化theme的类型定义,比{[key:string]: topBarType}校验更严格 const theme: Record<variantTypes, topBarType> = { sm: { height: `height:2rem;`, "font-size": `font-size: 1.5rem;`, iconWidth: `width: 1.75rem;`, iconHeight: `height: 1.75rem;`, }, md: { height: `height:2.5rem;`, "font-size": `font-size: 1.75rem;`, iconWidth: `width: 2rem;`, iconHeight: `height: 2rem;`, }, lg: { height: `height:3rem;`, "font-size": `font-size: 2rem;`, iconWidth: `width: 2.5rem;`, iconHeight: `height: 2.5rem;`, }, }; if (!variant) return theme["lg"][property]; return theme[variant][property]; }
兜底兼容方案
如果你确实需要支持传入任意字符串作为property,不愿意做严格的类型收窄,可以给topBarType加上字符串索引签名,不过该方案会丢失类型校验能力,不推荐优先使用:
type topBarType = { [key: string]: string; // 新增字符串索引签名 height: string; "font-size": string; iconWidth: string; iconHeight: string; };
内容的提问来源于stack exchange,提问作者Himanshu Singh
相关产品推荐
相关产品推荐

