如何让TypeScript函数根据参数返回对应Resume接口的数组类型?
问题
现有用于构建简历的分段接口IWorkExperience、IEducation,以及整合这些分段的IResume接口,需要实现getSectionDataByType函数,使其根据传入的类型参数返回对应接口的数组类型,当前函数返回any[]不符合预期。相关代码如下:
export interface IWorkExperience { unique: string; jobTitle: string | null; company: string | null; city: string | null; country: string | null; from: string | null; to: string | null; description: string | null; position: number; height: number; } export interface IEducation { unique: string; school: string | null; field: string | null; degree: string | null; city: string | null; country: string | null; from: string | null; to: string | null; current: boolean; description: string | null; position: number; height: number; } export interface IResume { workExperiences: IWorkExperience[]; educations: IEducation[]; } export const getSectionDataByType = (type: string, resume: IResume): any[] => { let section: any; Object.keys(resume).map((k, i) => { if (k === type) { section = resume[k as keyof typeof resume]; } }); return section; }
请问如何修改该函数,使其正确返回IWorkExperience[]或IEducation[]类型?
解决方案
可以通过限制参数类型为IResume的键名,并利用类型推断让函数返回对应类型的数组,同时简化冗余的遍历逻辑。修改后的代码如下:
export interface IWorkExperience { unique: string; jobTitle: string | null; company: string | null; city: string | null; country: string | null; from: string | null; to: string | null; description: string | null; position: number; height: number; } export interface IEducation { unique: string; school: string | null; field: string | null; degree: string | null; city: string | null; country: string | null; from: string | null; to: string | null; current: boolean; description: string | null; position: number; height: number; } export interface IResume { workExperiences: IWorkExperience[]; educations: IEducation[]; } // 修改后的函数 export const getSectionDataByType = <T extends keyof IResume>(type: T, resume: IResume): IResume[T] => { return resume[type]; }
关键修改说明:
- 泛型约束参数:用
T extends keyof IResume限制type只能传入IResume中存在的键名(即"workExperiences"或"educations"),避免无效输入。 - 自动推断返回类型:返回类型指定为
IResume[T],TypeScript会根据传入的type自动匹配对应的数组类型,无需手动标注。 - 简化逻辑:直接通过键名访问
resume的属性,去掉不必要的遍历操作,代码更高效简洁。
使用示例:
const resume: IResume = { workExperiences: [], educations: [] }; // 自动推断返回IWorkExperience[]类型 const workData = getSectionDataByType("workExperiences", resume); // 自动推断返回IEducation[]类型 const eduData = getSectionDataByType("educations", resume);
内容的提问来源于stack exchange,提问作者Burak Emre Kadan
相关产品推荐
相关产品推荐

