简体   繁体   中英

Cannot find error while destructuring arguments in TypeScript

I'm porting some code to TypeScript, and a bit stumped by this error. The SomeObject type is supposed to allow an object with any named keys which equate to string values. When using in unpacked argument fields, I get two errors:

'SomeObject' is declared but its value is never read.

and

Cannot find name 'someArg'. Did you mean the instance member 'this.someArg'?

Here's the code:

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

class SomeClass {

  someArg: SomeObject

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

module.exports = SomeClass;

Here you can see where TypeScript has a problem in VS Code:

在此处输入图片说明

Am I missing something? I would expect to be able to create an instance of this class like so:

new SomeClass({someArg: {hello: 'world'}}) // Passes TypeScript

new SomeClass({someArg: {hello: 1}}) // Fails TypeScript as value is not a string

You need to declare your type in this way:

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

class SomeClass {

  someArg: SomeObject

  constructor({ someArg }: { [key: string]: SomeObject } = {}) {
    this.someArg = someArg
  }
}

Since someArg is optional, you should use indexed type, or you can use Record<string, SomeObject> instead of { [key: string]: SomeObject }

UPDATE

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

More about destructuring in Typescript you can find in this article

Remove you {} and use...

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;

Does that work for your use case?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM