Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to satisfy the constraint of Record<string, unknown> with interface

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.

like image 696
Raph117 Avatar asked Aug 27 '20 13:08

Raph117


1 Answers

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
}
like image 198
Anthony Avatar answered Nov 10 '22 13:11

Anthony