40

Is it possible to write an interface that accepts a string constant as one of its parameters, and uses that as the key of an object?

For instance, assuming I make two different GraphQL requests, both of which return a User, but under different key names:

const userByIdResult = {
  data: {
    userById: {
       id: 123,
       username: 'joseph'
    }
  }
}

const userByUsernameResult = {
  data: {
    userByUsername: {
       id: 123,
       username: 'joseph'
    }
  }
}

I would imagine writing a generic interface would go something like this:

interface GraphQLResponse<QueryKey, ResponseType> {
  data: {
    [QueryKey]: ResponseType
  }
}

interface User {
    username: string
    id: string
}

type UserByIdResponse = GraphQLResponse<'userById', User>
type UserByUsernameResponse = GraphQLResponse<'userByUsername', User>

But, this doesn't work.

1 Answer 1

55

You're close. This falls under the category of Mapped Types. You need to make two changes:

  1. QueryKey extends string
  2. 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'
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for a good explanation! I was completely baffled by this because [key in x] makes it sound like you are looping through an array so I was a little thrown.

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.