Skip to content
Advertisement

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:

enter image description here

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

Advertisement

Answer

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

Advertisement