typescript - 基于输入对象字段的函数的通用返回类型
问题描述
我想要一个基于 Input 对象的返回类型。我们在函数中实现了一个猫鼬风格的字段选择器,我想实现依赖于输入对象字段的返回类型。
以下代码示例应说明问题:
interface IFields {
_id: number;
name: string;
value1: string;
value2: string;
value3: string;
value4: string;
value5: string;
value6: string;
}
export interface IFieldsSelector<T> {
fields: {
[key in keyof T]?: boolean;
};
}
interface IResult extends IFields{ }
const select = (payload: IFieldsSelector<IFields>): IResult => {
return {} as IResult;
};
const result = select({
fields: {
_id: true,
value1: true,
}
});
result.value1; // ok
result._id; // ok
result.name // error
解决方案
我们可以将输入键定义为泛型类型参数(打字稿会推断它),然后从以下位置选择它们IFields
:
export interface IFieldsSelector<T extends PropertyKey> {
fields: {
[key in T]?: boolean;
};
}
interface IResult extends IFields { }
const select = <T extends keyof IFields>(payload: IFieldsSelector<T>): Pick<IFields, T> => ({} as IResult);
const result = select({
fields: {
_id: true,
value1: true,
}
});
result.value1; // ok
result._id; // ok
result.name // now error
推荐阅读
- python - plotfile 没有使用正确的轴,注释问题
- laravel - Laravel 5.5 路线本地化
- hibernate - 带有空间搜索的休眠搜索多对多
- c# - 检测未触发的对象是否不在 Trigger Unity 3D 中
- or-tools - 谷歌 OR-Tools 根据站点安排单个工人和团体的访问
- shiny - 如何修改闪亮主题的主题?
- python - 将终端命令缩短为脚本
- tensorflow - 如何在我的 Keras 模型中使用谷歌提供的 What If Tool (WIT)?
- sql - Raws into Strings in Columns - 仅当两个后续是唯一的
- scala - 单元测试火花数据帧转换链接