I'm using Typeorm and want to strongly type my raw entity results.
Let's say I know I have a class called User
class User {
id: string;
name: string;
age: number;
}
When fetching raw entities in typeorm, which is sometimes useful for complex queries with performance issues, the result will be prefixed with a chosen alias in a returned piece of JSON, like so:
{ u_id: "1", u_name: "Hello", u_age: 23; }
Given that I know the keys in the User class, how can I use template literal types to create an interface corresponding to the returned JSON?
What I've tried:
type RawUser = { [K in `u_${keyof User}`]: User[K] };
Which won't work, obviously, as K is u_id, u_name etc which cannot index the User type.
The answer is:
type RawUser = { [K in keyof User as `u_${K}`]: User[K] };
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.