Typescript基于接口从另一个对象创建对象
我想从另一个对象创建一个Typescript基于接口从另一个对象创建对象,typescript,Typescript,我想从另一个对象创建一个ExampleInterface对象,但只保留ExampleInterface包含的那些属性 是否可以不手动复制每个密钥 export interface ExampleInterface { property1: string; property2: string; } 然后 const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties; 提前感谢。一个可能的解决方案是使
ExampleInterface
对象,但只保留ExampleInterface
包含的那些属性
是否可以不手动复制每个密钥
export interface ExampleInterface {
property1: string;
property2: string;
}
然后
const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;
提前感谢。一个可能的解决方案是使用上述功能:
function createExampleInterface(sourceObject: ExampleInterface): ExampleInterface
{
const emptyExampleInterface: ExampleInterface = {
property1: '',
property2: ''
};
const interfaceProperties = Object.keys(emptyExampleInterface);
const targetObject: ExampleInterface = Object.assign({}, sourceObject) ;
for (let property of Object.keys(targetObject)) {
if (interfaceProperties.indexOf(property) < 0) {
delete targetObject[property];
}
}
return targetObject;
}
在中尝试一下,因此我认为类可能是更好的选择,因为在那里您可以创建一个构造函数,并将另一个对象作为参数提供给它,如下所示:
export class ExampleDomainObject {
constructor(obj: AnotherObjectThatHasMoreProperties) {
this.myProp = obj.myProp;
// here you apply all properties you need from AnotherObjectThatHasMoreProperties
}
}
如果有帮助,请告诉我:)TypeScript类型不生成运行时类型,因此开箱即用您无法做到这一点。为什么需要在运行时剥离额外的属性?可能最简单的解决方案是创建一个手动复制所需属性的函数。还有,它们可能会有所帮助。可能的重复虽然在我的案例中,我选择了“类而不是接口并使用构造函数”解决方案,但我认为这个答案对我的问题是正确的。是的,最后我承认类比接口更适合我的案例,谢谢。)很高兴这有帮助:)
export class ExampleDomainObject {
constructor(obj: AnotherObjectThatHasMoreProperties) {
this.myProp = obj.myProp;
// here you apply all properties you need from AnotherObjectThatHasMoreProperties
}
}