18

My linter is saying I shouldn't use object as a type in TS. However, a library that I'm using asks for generic types that extend object.

I'm therefore writing a generic component with the library that looks like this:

const Component = <T extends object>(props: CustomProps<T>): React Element => etc. 

Since the linter is complaining, I've tried switching it to

const Component = <T extends Record<string, unknown>>(props: CustomProps<T>): React Element => etc. 

However, if I then do something like this:

interface MyInterface {
  something: string;
  goes: number; 
  here: string;
}

const CallerComponent = () => Component<MyInterface> />

TS says that MyInterface does not satisfy the constraint Record<string, unknown>. Is there any way around this other than to do

interface MyInterface extends Record<string, unknown>

I'd rather not have to go through the entire codebase adding this to every interface so it would be great to know if there's a way I can type it where I say that T will definitely be an object.

Thanks in advance for any help.

8
  • 14
    Record<string, unknown> will require an index signature. Why didn't object work for you ? You could also try T extends Record<keyof T, unknown>. Commented Aug 27, 2020 at 13:55
  • Hi Titian, thanks for this - eslint has a rule against using object. I'll try your suggestion.
    – Raph117
    Commented Aug 27, 2020 at 14:19
  • 1
    take eslint rules with a grain of salt. They are there to prevent people jumping the gun, but in this case object might be fine Commented Aug 27, 2020 at 14:38
  • OK thanks - just knowing that is actually very helpful. I might just ignore this line and come back to it if I have the time
    – Raph117
    Commented Aug 27, 2020 at 15:20
  • 1
    @LindaPaiste if the problem is with ESLint, the type {} also gives an error.
    – David
    Commented Mar 18, 2021 at 9:15

1 Answer 1

24

I ran into the same issue and found that you can declare your object with type instead of interface and it solves it.

In your case it would be :

type MyInterface = {
  something: string
  goes: number
  here: string
}
2
  • 1
    This fixed the same issue for me. I hate that this is the case, though -- I don't really get it, TBH.
    – James Nail
    Commented Aug 18, 2022 at 21:00
  • 2
    You may find a bit more detail on this here and here Commented Apr 27, 2023 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.