当属性名称相同时,如何使用typescript将对象映射到另一个接口类型



如果我有IInterface1,并且我有一个类型的对象数组

export interface IInterface1 {
id: string;
status: string;
otherStatus: string;
title: string;
person: string;
needed: IThisOtherInterface[];
}

然后我有另一个接口IInterface2

export interface IInterface2{
id: string;
status: string;
otherStatus: string;
title: string;
person: string;
needed: IThisOtherInterface2[];
}

然后,我想将类型为IInterface1的数组中的所有对象转换为IInterface2——数据相同,但我无法编辑IInterface1。如何使用typescript实现这一点?

如果数据相同,那么问题在哪里?类型在运行时不存在。我不明白为什么

list1 as IInterface2[]

不会起作用。

只需使用es6语法(如:(就可以更容易地实现

let firstTypeObject = {
id: 1,
status: "Active",
title: "Mr"
};
let secondTypeObject = {...firstTypeObject};

最新更新