javascript - 过滤 Typescript 中的现有对象属性
问题描述
我在打字稿中有一个any
对象,我需要对其进行整形,以便它对给定的界面有效。
我需要一种方法来创建新对象,以清除不属于类定义的属性,并添加缺少的属性。
代码示例可能是:
interface ImyInterface {
a: string;
b: string;
c?:string;
};
let myObject = {
a: "myString",
d: "other value"
};
我的问题是:有没有一种方法可以转换/过滤myObject
,使其适合接口ImyInterface
定义,并转换为此
console.log (JSON.stringify(objectA));
> {a: 'myString', b: null}
解决方案
可能有更好的方法,但在我的脑海中这是可行的:
let otherObject: ImyInterface = { a: null, b: null };
let x: ImyInterface = { ...otherObject, ...myObject };
第一行定义了所需接口的对象。
第二行定义了所需接口的新对象,并将所有属性复制到该对象中otherObject
,然后从该对象中复制myObject
符合接口的任何属性。
注意:如果你只用这个试试:
let x: ImyInterface = { ...myObject };
您将看到接口的某些属性丢失的错误。因此首先创建一个“完整”对象的原因(otherObject
在我的示例中)。
推荐阅读
- npm - 意外的 npm 发布后,我的代码是否会永久发布在互联网上?
- python - 如何使用随机数创建嵌套列表?
- google-apps-script - Google Sheets + Apps 脚本:如何根据单元格的值按名称删除工作表
- java - Tyk API 网关每 60 秒重试一次请求
- java - 如何在另一种方法中使用变量?
- r - 如何按照 R 中的属性顺序对向量进行排序?
- c# - 访问属性属性的更短方法,无需访问它两次
- java - 最大堆和最小堆初始化 (Java) 优先级队列
- spring-boot - 如何在 Lettuce 6 Spring Boot 2.4 中配置客户端缓存
- android - nativescript 在远程模拟器上运行代码