我有很多接口,如 IWorkExperience、IEducation 等,用于构建简历接口(IResume)。我有很多用于简历部分的接口,但给定的接口是例如。请看下面的接口;
我正在尝试获取项目(接口类型的数组)作为函数的返回类型。
这是我的函数没有按预期工作。
如何获取 IWorkExperience 或 IEducation 的类型作为此函数的返回类型以获取 resume 中的项目?
谢谢。
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;
}```
我已经通过使用联合类型解决了这个问题。我将发布我的解决方案,以防其他人遇到同样的问题。您可以找到playground解决方案。
type EntityType = "workExperiences" | "educations";
function getItems<T extends EntityType>(type: T, resume:IResume) {
return resume[type];
}
const a = getItems("workExperiences", resume);
const b = getItems("educations", resume);