TypeScript中拆分字符串获键赋值keyof报错,原因及解决方法
TypeScript类型不匹配问题解析与修复
问题现象
第一段代码可以正常运行:
interface Lol { haha?: string; } let key: keyof Lol = 'haha'; let lol: Lol = {} lol[key] = 'har har!';
但第二段代码会抛出类型错误:type 'string' is not assignable to type "haha".(2322)
interface Lol { haha?: string; } let str = 'haha.waffle' let key: keyof Lol = str.split('.')[0]; let lol: Lol = {} lol[key] = 'har har!';
为什么会报错?
TypeScript是静态类型语言,编译阶段就会做类型检查。str.split('.')[0]返回的类型是通用的string,而key的类型是keyof Lol——也就是字面量类型"haha"。
虽然运行时str.split('.')[0]的值确实是"haha",但TypeScript编译时没办法确定这个字符串一定是Lol接口的键名,所以会判定类型不兼容,抛出错误。
怎么修复?
这里有两种实用的修复方式:
方式一:类型断言
直接给str.split('.')[0]加上类型断言,告诉TypeScript它的类型就是keyof Lol:
interface Lol { haha?: string; } let str = 'haha.waffle' let key: keyof Lol = str.split('.')[0] as keyof Lol; let lol: Lol = {} lol[key] = 'har har!';
方式二:类型守卫(更严谨)
如果想要确保值的正确性,避免运行时出错,可以添加类型守卫做检查:
interface Lol { haha?: string; } let str = 'haha.waffle' const candidateKey = str.split('.')[0]; let key: keyof Lol; if (candidateKey === 'haha') { key = candidateKey; let lol: Lol = {} lol[key] = 'har har!'; } else { // 这里可以处理键名不符合的情况,比如抛出错误 throw new Error('键名不符合Lol接口的要求'); }
内容的提问来源于stack exchange,提问作者patrick
相关产品推荐
相关产品推荐

