1

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?

1 Answer 1

3

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

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.