Home > Net >  Typescript generic associative array
Typescript generic associative array

Time:08-06

I would like to get deep value from the object, for example result when generic is "books":

fieldName: {author: "", langauge: "", translation: ""}
export const COLLECTIONS_MOCKUP = {
   books: {
      author: "",
      language: "",
      translation: "",
   },
   vehicle: {
      model: "",
      type: "",
      color: "",
   },
}

export interface IOptionalField<T> {
   fieldName: typeof COLLECTIONS_MOCKUP[T]; // how to make it work, it throws an error
   valueType: string | number | boolean | Date;
   isAdded?: boolean;
}

CodePudding user response:

You need a generic constraint, so that T must be a key of COLLECTIONS_MOCKUP.

export interface IOptionalField<T extends keyof typeof COLLECTIONS_MOCKUP> {
   fieldName: typeof COLLECTIONS_MOCKUP[T];
   valueType: string | number | boolean | Date;
   isAdded?: boolean;
}

This works as you expected:

const books: IOptionalField<"books"> = {
    fieldName: {
        author: "",
        language: "",
        translation: ""
    },
    valueType: 0
}

Playground

  • Related