网站搜索

javascript - 在 TypeScript 中解构参数时找不到错误


我正在将一些代码移植到 TypeScript,对于这个错误有些困惑。SomeObject 类型应该允许具有任意命名键且对应字符串值的对象。在使用展开参数字段时,我遇到了两个错误:

‘SomeObject’ 已声明,但其值从未被读取。

和

找不到名称 'someArg'。你是想指实例成员 '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

答案#1

你需要以这种方式声明你的类型:

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 中解构的信息

答案#2

移除你的 {} 并使用...

type SomeObject = { [key: string]: string; }

class SomeClass {

  someArg: SomeObject

  constructor (someArg: SomeObject = {}) {
    this.someArg = someArg
  }
}

class fred {

    fredJnr:SomeClass = new SomeClass( { Hello: "fred"})
}
module.exports = SomeClass;

这适合你的使用场景吗?