3

I am trying to write a generic interface which accepts two types, something returned by Entry, T and the key, K which contains this.

I am not sure if this is something that can be done using typescript.

Does anyone know? Thanks!

// this is a bad way of doing it
export interface Reconfigure<T> {
  title: string
  keyOne?: Entry<T>[]
  keyTwo?: Entry<T>[]
  keyThree?: Entry<T>[]
  keyFour?: Entry<T>[]
}

// this is close to what I'd want to do, but doesn't work
export interface Reconfigure<T, K> {
  title: string
  [K]: Entry<T>[]
}
4
  • You can do what you want with a type alias e.g. type Reconfigure<T, K> = { [key in K]: Entry<T> } but not sure if you can get it working as nicely as an interface. Commented Nov 20, 2019 at 12:55
  • As an aside, when you add the phrase "doesn't work" in a question, you should always show the not-working outcome (i.e. the error/warning that it causes). Commented Nov 20, 2019 at 13:02
  • Possible duplicate of TS(2352) Declare object with dynamic properties and one property with specific type Commented Nov 20, 2019 at 13:04
  • @spender I'm not sure about that. OP wants that eventually, K will be a specific property (for ex. for K = 'foo', the interface will has the prop foo: Entry<T>[]}.. Commented Nov 20, 2019 at 13:10

1 Answer 1

1

You can use a mapped type. The predefined types Record and Partial should let you to create a type based on a union of string literal types. Adding the fixed part of the type is just a matter of using an intersection type (&):

export type Reconfigure<T, K extends PropertyKey> = Partial<Record<K, Entry<T>>> &  {
    title : string
}

type T = Reconfigure<string, "k1" | "k2" | "k4">
// same as
// type T = {
//     k1?: Entry<string> | undefined;
//     k2?: Entry<string> | undefined;
//     k4?: Entry<string> | undefined;
//     title: string;
// }

Playground Link

Sign up to request clarification or add additional context in comments.

1 Comment

This works for me and is pretty clean, thanks Titian!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.