15

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()
}

Any idea what type I should 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)

Thanks in advance

danday74
  • 52,471
  • 49
  • 232
  • 283
  • 1
    In this case such linter rule is useless.. – Aleksey L. Nov 16 '20 at 05:14
  • obviously, the whole function is useless - its just an example - thx – danday74 Nov 16 '20 at 10:09
  • Does this answer your question? [How can I solve this error 'don't use object as a type'?](https://stackoverflow.com/questions/64962822/how-can-i-solve-this-error-dont-use-object-as-a-type) – Aleksi Mar 11 '21 at 03:03

3 Answers3

8

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
7

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>
3

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 :)
    }
}
Aleksi
  • 4,483
  • 33
  • 45