我想ExampleInterface从另一个对象创建一个对象,但只保留ExampleInterface包含的那些属性。
是否可以不手动复制每个密钥?
export interface ExampleInterface {
property1: string;
property2: string;
}
Run Code Online (Sandbox Code Playgroud)
进而
const exampleObject: ExampleInterface = anotherObjectThatHasMoreProperties;
Run Code Online (Sandbox Code Playgroud)
提前谢谢你。
一个可能的解决方案是上面的函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用该函数的示例:
const objA = {
property1: 'Property 1',
property2: 'Property 2',
property3: 'Property 3'
}
const objB: ExampleInterface = createExampleInterface(objA);
console.log(objB);
Run Code Online (Sandbox Code Playgroud)
在https://stackblitz.com/edit/typescript-rjgcjp中尝试一下
| 归档时间: |
|
| 查看次数: |
9558 次 |
| 最近记录: |