typescript - Typescript - 根据参数返回通用接口类型
问题描述
我有一个将数组转换为各种类型的javascript对象的方法,这些类型的接口类似于这些:
export interface IService1 {
header: string;
desc: string;
serviceID: number;
...
}
export interface IService2 {
footer: string;
desc: string;
serviceID: number;
otherStuff: string;
...
}
export interface IService3 {
container: string;
desc: string;
serviceID: number;
otherStuff: string;
...
}
我的转换方法是这样的:
function convArrayToObject(datatype: string, fields: string[]): any {
//logic here
}
参数是一个字符串,datatype
它与转换函数将返回的接口名称完全对应(IService1
、IService2
等IService3
) 为了方便起见,我将函数的返回类型设置为“任意”,但我想知道是否有方法使函数返回参数指示的特定类型datatype
。
我尝试了一些超载,但服务太多,我希望Generics
能来救援。我的服务都只是接口,所以任何获取实例或类似的调用都只是过度劳累
任何建议将不胜感激
解决方案
这应该有效:
function convArrayToObject(datatype: 'type1', fields: string[]): IService1;
function convArrayToObject(datatype: 'type2', fields: string[]): IService2;
function convArrayToObject(datatype: 'type3', fields: string[]): IService3;
function convArrayToObject(datatype: string, fields: string[]): any {
// logic here
}
编辑:另一种解决方案
interface RecordService {
type1: IService1;
type2: IService2;
type3: IService3;
}
function anotherOne<T extends keyof RecordService>(datatype: T, fields: string[]): RecordService[T] {
// logic here
}
const service2 = anotherOne('type2');
推荐阅读
- linux - 无法连接到存储库 SVN
- javascript - 如何将导入的 Slack 数据定位到 Google 表格的特定单元格中?
- android - 错误:无法访问 zzbgl 错误不断重新出现
- c - malloc 覆盖按值传递的参数
- twilio - 当用户进行特定选择时,我如何(使用 Twilio Functions 示例关键字处理程序)向外部网站发送 POST 请求?
- bash - 如何在分隔符上拆分字符串并将常量值附加到所有元素
- javascript - Javascript:我想根据用户提供的值刷新具有更改的代码结构(值字段)的页面
- sql - 根据条件结果执行 SQL 查询
- node.js - 如何在 Javascript 文件中导入 Typescript 文件并在使用前解释其内容?
- microsoft-teams - 将 MS Planner 选项卡添加到 MS Teams 中的群聊