我正在将一些代码移植到 TypeScript,但这个错误有点让我困惑。 SomeObject
类型应该允许对象具有任何等同于字符串值的命名键。在解压参数字段中使用时,出现两个错误:
'SomeObject' is declared but its value is never read.
和
Cannot find name 'someArg'. Did you mean the instance member 'this.someArg'?
代码如下:
type SomeObject = { [key: string]: string; }
class SomeClass {
someArg: SomeObject
constructor ({someArg: SomeObject} = {}) {
this.someArg = someArg
}
}
module.exports = SomeClass;
在这里你可以看到 TypeScript 在 VS Code 中出现问题的地方:
我错过了什么吗?我希望能够像这样创建此类的实例:
new SomeClass({someArg: {hello: 'world'}}) // Passes TypeScript
new SomeClass({someArg: {hello: 1}}) // Fails TypeScript as value is not a string
最佳答案
您需要以这种方式声明您的类型:
type SomeObject = { [key: string]: string; }
class SomeClass {
someArg: SomeObject
constructor({ someArg }: { [key: string]: SomeObject } = {}) {
this.someArg = someArg
}
}
自 someArg
是可选的,您应该使用索引类型,或者您可以使用 Record<string, SomeObject>
而不是{ [key: string]: SomeObject }
更新
type SomeObject = { [key: string]: string; }
class SomeClass {
someArg: SomeObject | undefined
constructor({ someArg }: { someArg?: SomeObject } & Record<PropertyKey, any> = {}) {
this.someArg = someArg
}
}
const x = new SomeClass({}) // ok
const y = new SomeClass({ age: 42 }).someArg // ok
const z = new SomeClass({ someArg: { age: '42' } }).someArg // ok
有关 Typescript 中解构的更多信息,您可以在 this article 中找到
关于javascript - 在 TypeScript 中解构参数时找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68498133/