Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript create key using a generic type

Tags:

typescript

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>[]
}
like image 706
userqwert Avatar asked Feb 26 '26 02:02

userqwert


1 Answers

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

like image 97
Titian Cernicova-Dragomir Avatar answered Feb 28 '26 17:02

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!