在我的项目中,我遇到了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/