Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map property of type any/unknown to generic type T

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading