Home > OS >  Map property of type any/unknown to generic type T
Map property of type any/unknown to generic type T

Time:07-07

If I have...

type TypeNonGeneric = { prop1: any, prop2: string };

How can I map this to...

type TypeGeneric<T> = { prop1: T, prop2: string };

I've looked at the docs and it seems that it needs to be a new generic type that would take TypeNonGeneric as a parameter, iterate over its keys and if a property type is any then it returns a "T" else leaves the type unchanged.

CodePudding user response:

I would use the IfAny utility type from this answer. We can then map over the passed type and check for any for each property.

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;

type TypeGeneric<O, T> = {
  [K in keyof O]: IfAny<O[K], T, O[K]>
}

Let's see an example:

type TypeNonGeneric = { prop1: any, prop2: string };

type Result = TypeGeneric<TypeNonGeneric, number>
// type Result = {
//    prop1: number;
//    prop2: string;
// }

or if you want to replace any with T

type Result2<T> = TypeGeneric<TypeNonGeneric, T>
// type Result = {
//    prop1: T;
//    prop2: string;
// }

Playground

  • Related