Home > OS >  Grouping multiple interfaces into a single interface in Typescript
Grouping multiple interfaces into a single interface in Typescript

Time:12-04

I'm trying to understand interfaces in Typescript, I can't quite get them to do what I want.

interface RequestData {
  [key: string]: number | string | File;
}

function makeRequest(data: RequestData) {
  // Do something with data...
}

interface UserRequestData {
  id: number;
  email: string;
  username: string;
}

function updateUser(userData: UserRequestData) {
  makeRequest(userData); // ERROR
}

// ERROR:
// Argument of type 'UserRequestData' is not assignable to parameter of type 'RequestData'.
//   Index signature for type 'string' is missing in type 'UserRequestData'.ts(2345)

interface ItemRequestData {...}
interface QueryRequestData {...}
// and more interfaces...

I have a several smaller interfaces such as UserRequestData, ItemRequestData, QueryRequestData that I want to group under a larger interface RequestData.

Since the smaller interfaces all have string keys and certain datatypes, I'd expect to be able to type all of them using {[key: string]: number | string | File;}, however that does not work.

How do I modify makeRequest, such that it is able to accept any interface that uses strings as keys and number | string | File as the value type?

CodePudding user response:

Using [key: string] in RequestData interface is an example of an index signature . That's only represents one property and not the entire smaller interface.

If you want makeRequest able to accept any interface you can use Extending Type. Something like:

interface RequestData {...}

interface UserRequestData extends RequestData {
  id: number;
  email: string;
  username: string;
}
interface ItemRequestData extends RequestData {...}
interface QueryRequestData extends RequestData {...}
  • Related