简体   繁体   中英

How to get typeof generic model's parameter inside of another type?

I have one interface which takes type T:

export interface ValueTimestampModel<T> {
    value: T;
    timestamp: string;
}

And I have a type which should use the above to transform a given model of type T by turning every parameter of T into ValueTimestampModel :

export type ModelWithTimestamp<T> = {
    [P in keyof T]?: ValueTimestampModel<typeof T[P]>
}

So the desired result would be -> if we have model:

{
   street: string;
   streetNo: number;
}

then ModelWithTimestamp version should be like:

{
   street: {
      value: string,
      timestamp: string
   },
   streetNo: {
      value: number,
      timestamp: string
   }
}

Unfortunately the part typeof T[P] returns the compilation error:

'T' only refers to a type, but is being used as a value here.

It seems typescript wont accept typeof in this context. Are there any alternatives to achieve what I'm looking for?

You don't need typeof , T[P] is already the type of property P in type T :

export interface ValueTimestampModel<T> {
    value: T;
    timestamp: string;
}


export type ModelWithTimestamp<T> = {
    [P in keyof T]?: ValueTimestampModel<T[P]>
}

Playground Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM