typescript 动态添加属性为什么不匹配扩展后的interface?
interface base {
hello: string
[key:string]:any
}
interface baseAdd extends base{
world: string
}
function test(p: baseAdd) {
console.log(p);
}
let error: base = {hello:'hello'}
error.world = 'world'
test(error) // 报错
/* Argument of type 'base' is not assignable to parameter of type 'baseAdd'.
Property 'world' is missing in type 'base' but required in type 'baseAdd'.ts(2345)
a.ts(6, 3): 'world' is declared here.
我觉得可能是-----[key:string]:any
的原因,然后请问如何修改才能让ts在动态修改属性后匹配上新的interface?除了test(error as baseAdd)
回复
1个回答

test
2024-07-11
let error: base = {hello:'hello'}
error.world = 'world'
即使你这么操作了,error
的类型也还是 base
,因为它符合[key:string]:any
你这是要将一个父类变成更具体的子类,据我了解应该只能用断言
但是如果反过来,这样是可以的
interface base {
hello: string
[key:string]:any
}
interface baseAdd {
hello: string
world: string
[key:string]:any
}
function test(p: base) {
console.log(p);
}
let error: baseAdd = {hello: '1', world: '2'}
test(error)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容