简体   繁体   English

Typescript 将模板文字类型映射为索引类型

[英]Typescript Mapped Template Literal Types as Index Type

I'm using Typeorm and want to strongly type my raw entity results.我正在使用 Typeorm 并希望强烈键入我的原始实体结果。

Let's say I know I have a class called User假设我知道我有一个名为 User 的 class

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:当在 typeorm 中获取原始实体时,这有时对具有性能问题的复杂查询很有用,结果将在返回的 JSON 片段中以选择的别名为前缀,如下所示:

{ 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?鉴于我知道用户 class 中的键,我如何使用模板文字类型来创建与返回的 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.显然,这是行不通的,因为 K 是 u_id、u_name 等,它们无法索引用户类型。

The answer is:答案是:

type RawUser = { [K in keyof User as `u_${K}`]: User[K] };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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