0

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.

Ian
  • 141
  • 1
  • 1
  • 7

1 Answers1

0

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

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
  • I want the type parameter to preserve on the new type. So TypeGeneric wouldn't take a second type parameter, it would add one to the resulting type and prop1 would be type T. – Ian Jul 06 '22 at 12:08
  • you can remove `O` from the generic type of `TypeGeneric` and replace it inside the map with `TypeNonGeneric` if you want – Tobias S. Jul 06 '22 at 12:15