Typescript - Generic Type - static key - Can we get the value from a static key in a type?

Viewed 44

Let's assume we have this code, what should be the best way to solve this type issue ?

type TypeA = {
  entityType: 'Type_A'
};

type TypeB = {
  entityType: 'Type_B'
};

type TypeAB = TypeA | TypeB;

const getOnlySubTypeTInArray = <T extends TypeAB>(TypeABs: TypeAB[]) => TypeABs.filter<T>(
  (doc: TypeAB): doc is T => doc.entityType === T.entityType,
);

const getTypeABs = (docs: TypeAB[]) : { typeAs: TypeA[], typeBs: TypeB[] } => ({
  typeAs: getOnlySubTypeTInArray(docs),
  typeBs: getOnlySubTypeTInArray(docs),
});

T.entityType create this error : 'T' only refers to a type, but is being used as a value here.ts(2693)

I would like that the line with { typeAs: TypeA[], types: TypeB[] } infer automatically the type of getOnlySubTypeTInArray without the need of specifying the type.

0 Answers
Related