jackdaw
jackdaw

Reputation: 2314

Typescript create key using a generic type

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>[]
}

Upvotes: 3

Views: 447

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

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

Upvotes: 1

Related Questions