我的界面如下:
interface TableColumn {
column: string;
returnType: any;
// some other fields, not relevant ...
constraints?: Constraints[];
}
interface Status extends TableColumn {
column: 'status';
returnType: string;
}
interface Title extends TableColumn {
column: 'title';
returnType: string;
}
interface PostProperties {
status: Status;
title: Title;
// and other properties...
}
我想使用以上内容来生成以下界面:
interface PostDbResponse {
status: string;
title: string;
}
我尝试使用映射类型和keyof
来实现此目的,但未能成功。甚至有可能这样做吗?
实际目标是使用架构数据从查询方法生成返回类型。但是,我也希望能够根据我们选择从哪个字段开始定义各种返回类型。
我可以使返回的响应中的所有字段为可选,但这并不理想。我愿意接受其他实施思路。
答案 0 :(得分:1)
这应该有效:
type PostDbResponse = {
[K in keyof PostProperties]: PostProperties[K]["returnType"]
};
对于K
的每个键PostProperties
(例如status
),我们采用K
的属性PostProperties
的类型(例如, Status
),然后是该类型的returnType
属性的类型。