You’re close. This falls under the category of Mapped Types. You need to make two changes:
QueryKey extends string
key in QueryKey
interface GraphQLResponse<QueryKey extends string, ResponseType> {
data: {
[key in QueryKey]: ResponseType;
}
}
interface User {
username: string;
id: number;
}
type UserByIdResponse = GraphQLResponse<'userById', User>;
type UserByUsernameResponse = GraphQLResponse<'userByUsername', User>;
Example Usage
const userByIdResult: UserByIdResponse = {
data: {
userById: {
id: 123,
username: 'joseph'
}
}
}
const userByUsernameResult: UserByUsernameResponse = {
data: {
userByUsername: {
id: 123,
username: 'joseph'
}
}
}
const userByIdResultBoom: UserByIdResponse = {
data: {
userByUsername: {
id: 123,
username: 'joseph'
}
}
}