Home > Back-end >  TypeScript ability to use a type's value and derive other value from keying off of type/interfa
TypeScript ability to use a type's value and derive other value from keying off of type/interfa

Time:04-10

type ListThemes =
  | "projects"
  | "data"
  | "alerts"
  | "jobs";

type ListDataType = {
  projects: ProjectListFieldsTypeMap;
  data: DataListFieldsTypeMap;
  alerts: AlertsListFieldsTypeMap;
  jobs: JobListFieldsTypeMap;
};

type ListProps = {
  theme: ListThemes;
  data: DERIVED_TYPE_HERE;
};

DERIVED_TYPE_HERE would be the value of ListDataType[theme]

Have made attempts to more directly tie ListThemes to the keys in ListDataType, but was not able to do so and still directly create a 1:1 relationship.

CodePudding user response:

something like this with generics might achieve your goal as I'm reading it:

type ListProps<T extends ListThemes> = {
  theme: T;
  data: ListDataType[T];
};

and you could also condense it and get rid of type ListThemes like:

type ListProps<T extends keyof ListDataType> = {
  theme: T;
  data: ListDataType[T];
};

but this won't work with the code you've given as GraftListThemes isn't defined, so I'm not sure what it's referring to, and entities doesn't map to anything in ListDataType.

  • Related