typescript - 使用[key : string]时, typescript 编译错误

标签 typescript compiler-errors

在我的项目中,我遇到了ts编译错误,然后进行了一个简单的演示:
像这样的代码

    interface ITest {
    getAddress: Function,
    [keys: string]: {
        name: string
        // [keys: string]: string //open this
     }
    }

    const person : ITest = {
    john: {
        name: "john"
    },
    getAddress: ()=>{
        //....
      }
    }

我工作正常,但是当我重新打开提交行时,
ts compile告诉错误:

 couldn't assign () => void to { [keys: string]: string; name: string; }

我不为什么我会收到此错误或。但是我必须这样使用。

我认为这是一个 typescript 编译错误?还是[keys:string]列表应该是同一类型?

我的 typescript 版本:3.8.3

最佳答案

好吧,不是,这不是错误。您取消注释的行会强制所有属性使每个属性成为字符串。

interface ITest2 {
  getAddress: {
    name: string, // this is required
    foo: int // error has to be string,
    bar: string // ok
  },
  someOther: {  // error because has no name property
    baz: string
  },
  another: {
    name:string // valid
  },
  [keys: string]: {
    name: string
    [keys: string]: string
  }
}

关于typescript - 使用[key : string]时, typescript 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61768906/

相关文章:

typescript - 使用 TypeScript 声明内联对象的类型

java - 在类名后添加冒号会导致错误吗?

c++ - 通过宏检查错误

c++ - kbhit 测试编译失败 'cannot find -lcurses'

c++ - 尝试使用 G++ 使用 openCV 进行编译后 G++ 返回错误

xml - 构建SLN : CS0008 - CS0115的奇怪错误

typescript - react-templates、TypeScript 和 webpack 之间的和谐

javascript - sublime text 3 中 typescript 的构建系统不起作用

javascript - 失去对 socket.io 中套接字的引用

javascript - 这个 typescript 方案是什么意思?