Jesse Winton
Jesse Winton

Reputation: 706

Using Typescript generic as key in interface

I'm trying to extend ParsedUrlQuery allowing for any key to be passed in. Right now I'm creating individual interfaces for a multitude of different parameters, like this:

export interface IdParams extends ParsedUrlQuery {
  id: string;
}

export interface SlugParams extends ParsedUrlQuery {
  slug: string;
}

What I want to do is creating something reusable that would allow me to do something similar to this:

export interface GenericParams<key, value> extends ParsedUrlQuery {
  [key]: value;
}

So I could use it anywhere like:

GenericParams<"slug", string>

or

GenericParams<"id", string[]>

depending on the needs of the page. Is that possible?

Upvotes: 1

Views: 1732

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187242

You need to use a mapped type here, which can't be an interface. But it should work fine as a type. The magic here is constraining the key to string, and using [key in K] to define the key type.

export type GenericParams<K extends string, V> = ParsedUrlQuery & {
  [key in K]: V;
}

type TestA = GenericParams<"slug", string> // { slug: string }
type TestB = GenericParams<"id", string[]> // { id: string[] }

See playground

Upvotes: 3

Related Questions