typescript - TS : Index signature for type 'string' is missing in type 'IParam'

标签 typescript

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/

相关文章:

reactjs - 如何在 createContext 中为 TypeScript 初始化 useState 的 set 函数?

typescript - 使handleRequest成为passportjs守卫上的异步方法

requirejs - TypeScript:扩展已通过 require 加载的类

reactjs - dockerized React 应用程序中的 VSCode + Typescript

angular - 如何在 ngBootstrap 和 Angular 中监听模态的关闭事件?

javascript - 如何在 Angular 2 应用程序中嵌入 javascript 组件?

typescript :为什么函数参数上的不同数据类型不会引发错误?

angular - 让用户 : User = new User (. ...) 为什么这对我不起作用?

javascript - Angular2 intelliJ 配置错误..找不到模块 '@angular/core'

javascript - Dom 元素未定义