danday74
danday74

Reputation: 56936

Don't use object as a type

I am getting the lint error:

don't use object as a type

When I use object as a type, example follows:

export const myFunc = (obj: object): string => {
  return obj.toString()
}

What type should I give to an object with unknown properties?

If it helps the object in question is NOT an array (which I know is strictly an object in JS).

Upvotes: 15

Views: 15791

Answers (3)

Aleksi
Aleksi

Reputation: 5016

Here's a concrete example of why the linter rule advices against using the object type:

function foo(obj: object) {
    for (const key in obj) {
        const val = obj[key]; // Compilation error: type 'string' can't be used to index type '{}'
    }
}

function bar(obj: { [key: string]: unknown }) {
    for (const key in obj) {
        const val = obj[key]; // works :)
    }
}

Upvotes: 3

I think that the best approach here is to use generic:

export const myFunc = <T extends { toString: () => string }>(obj: T): string => {
    return obj.toString()
}

myFunc(2) // no error
myFunc({}) // no error

If you want restrict your arguments to only object, then yes, @Evert's solution is Ok. But for the sake of type safety it is better to use unknown instead of any:

Record<string, unknown>

Upvotes: 8

Evert
Evert

Reputation: 99525

There's a few different ways to do this. Generally I feel the need for this is a bit of an anti-pattern.

But I would probably go for Record<string, any>, if that covers it for you.

Upvotes: 8

Related Questions