TypeScript修改接口对象索引值时出现类型错误的求助
问题:TypeScript赋值符号左侧报错
我是TypeScript初学者,不清楚为什么TypeScript会在赋值符号左侧报错。
原代码如下:
const nonMandatoryFields = [ 'address', 'mobilePhone', 'postCode', 'state', 'suburb', 'testMode', ]; interface XeroClientData { address: string; firstName: string; lastName: string; suburb: string; postCode: string; state: string; country: string; mobilePhone: string; email: string; recordId: string; testMode: boolean; } const sanitiseFields = (fields: XeroClientData) => { for (const key of nonMandatoryFields) { // 左侧报错 // 元素隐式拥有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型 "XeroClientData" fields[key] = fields[key as keyof XeroClientData] ? fields[key as keyof XeroClientData] : ''; } return fields; };
可以看到,我尝试用keyof操作符,右侧能正常工作,但左侧还是报错,希望有人能指出问题或提供解决思路,谢谢!
解决方法
感谢@jcalz的帮助,我已经解决了问题,代码如下:
const nonMandatoryFields = [ 'address', 'mobilePhone', 'postCode', 'state', 'suburb', ] as const; type NonMandatoryField = typeof nonMandatoryFields[number]; interface XeroClientData { address: string; firstName: string; lastName: string; suburb: string; postCode: string; state: string; country: string; mobilePhone: string; email: string; recordId: string; testMode?: boolean; // 可选属性 } const sanitiseFields = (fields: XeroClientData) => { nonMandatoryFields.forEach(<K extends NonMandatoryField>(key: K) => { fields[key] = fields[key] ? fields[key] : ''; }); return fields; };
关键解决点:
- 给
nonMandatoryFields添加as const断言,让TypeScript推断出数组元素是具体的字面量类型,而非宽泛的string类型 - 基于数组定义
NonMandatoryField类型,确保遍历的键都是XeroClientData中存在的属性 - 将
testMode改为可选属性,避免赋值空字符串时出现boolean与string的类型冲突 - 使用
forEach并通过泛型约束键的类型,确保赋值时左右两侧类型完全匹配
内容的提问来源于stack exchange,提问作者ph222123
相关产品推荐
相关产品推荐

