don't use object as a type
Asked Answered
U

3

16

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

Undetermined answered 16/11, 2020 at 4:0 Comment(3)
In this case such linter rule is useless..Professionalism
obviously, the whole function is useless - its just an example - thxUndetermined
Does this answer your question? How can I solve this error 'don't use object as a type'?Returnable
F
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.

Franky answered 16/11, 2020 at 4:51 Comment(0)
A
8

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>
Abecedary answered 16/11, 2020 at 7:36 Comment(0)
R
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 :)
    }
}
Returnable answered 11/3, 2021 at 3:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.