0

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?

1 Answer 1

1

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 {...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.