I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements.
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 multiple smaller interfaces like UserRequestData
, ItemRequestData
, QueryRequestData
that I intend to organize under a larger interface called RequestData
.
Given that the smaller interfaces all possess string keys and specific datatypes, I assumed I could define them all using
{[key: string]: number | string | File;}
; however, this approach appears to be ineffective.
How can I adjust makeRequest
so that it can accept any interface utilizing strings as keys and number | string | File
as the value type?