interface Param {name: string, age: number}
const p: Param = {name: 'tt', age: 18}
const foo = (object: {[key: string]: unknown}) => {
// ...something
}
foo(p)
// Argument of type 'Param' is not assignable to parameter of type '{ [key: string]: unknown; }'.
Index signature for type 'string' is missing in type 'Param'.
我传入的类型和函数参数的类型一致,为什么会报错?
最佳答案
您的动态参数应该是any
,而不是unknown
const foo = (object: {[key: string]: any}) => {
// ...something
}
您可以查看this document为了更好地理解未知
类型
[..] Much like any, any value is assignable to unknown; however, unlike any, you cannot access any properties on values with the type unknown, nor can you call/construct them. Furthermore, values of type unknown can only be assigned to unknown or any.
这意味着您无法将值分配给代码中的unknown
foo(p) //assign values to `unknown` type params
关于typescript - TS : Index signature for type 'string' is missing in type 'IParam' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71491974/