gpt4 book ai didi

typescript 基于接口(interface)从另一个对象创建一个对象

转载 作者:行者123 更新时间:2023-12-04 13:39:25 25 4
gpt4 key购买 nike

我想创建一个 ExampleInterface来自另一个对象的对象,但只保留那些 ExampleInterface 的属性包含。

是否可以不手动复制每个 key ?

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;
}

使用该函数的示例:
const objA = {
property1: 'Property 1',
property2: 'Property 2',
property3: 'Property 3'
}

const objB: ExampleInterface = createExampleInterface(objA);

console.log(objB);

试试看 https://stackblitz.com/edit/typescript-rjgcjp

关于 typescript 基于接口(interface)从另一个对象创建一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59753975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com