Home > database >  Keeping two fields of a type "in-sync"? Foo<X> (x:X implies y: Y)
Keeping two fields of a type "in-sync"? Foo<X> (x:X implies y: Y)

Time:04-06

I am wondering how to get two types to "correlate"? As in the following example, I only want to allow TypeContent to be of a type that makes sense for the type T.

export type DataReport<T extends Type, TypeContent> = {
  id: number
  createdAtDateTime: Iso8601DateTime
  contentType: T
  content: TypeContent // should depend on T somehow
}

If I could have used a javascript map, it would be something like

TypeMap = {
   Questionnaire: { id: string, items: QuestionnaireItem[] }
   BloodSample:  { dueDate: Iso8601DateTime }
}

const TypeContent = TypeMap[Type] // Type = BloodSample or Questionnaire

Is this possible to express in Typescript somehow?

CodePudding user response:

You can just use a type map the same, using indexed access types.

type TypeMap = {
  Questionnaire: { id: string, items: QuestionnaireItem[] }
  BloodSample:  { dueDate: Iso8601DateTime }
}

type Types = keyof TypeMap

export type DataReport<T extends Types> = {
  id: number
  createdAtDateTime: Iso8601DateTime
  contentType: T
  content: TypeMap[T]
}

type Test = DataReport<'Questionnaire'>
// => 
{
    id: number;
    createdAtDateTime: Iso8601DateTime;
    contentType: "Questionnaire";
    content: {
        id: string;
        items: QuestionnaireItem[];
    };
}

See this on TS Playground

  • Related