如何减少JavaScript对象以仅包含接口中的属性 [英] How to reduce javascript object to only contain properties from interface

查看:65
本文介绍了如何减少JavaScript对象以仅包含接口中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用打字稿时,声明的接口可能看起来像这样:

When using typescript a declared interface could look like this:

interface MyInterface {
  test: string;
}

具有额外属性的实现可能是这样的:

And an implementation with extra property could be like this:

class MyTest implements MyInterface {
  test: string;
  newTest: string;
}

示例(此处的变量"reduced"仍然包含属性"newTest"):

Example (here the variable 'reduced' still contain the property 'newTest'):

var test: MyTest = {test: "hello", newTest: "world"}

var reduced: MyInterface = test; // something clever is needed

问题

通常,如何使'reduced'变量仅包含在'MyInterface'接口中声明的属性.

In a general way, how can you make the 'reduced' variable to only contain the properties declared in the 'MyInterface' interface.

为什么

当尝试将'reduced'变量与angular.toJson一起使用之前,将其发送到Rest服务时会发生问题-toJson方法转换newTest变量,即使在编译期间实例上不可访问它也是如此. REST服务不接受JSON,因为它具有不应存在的属性.

The problem occur when trying to use the 'reduced' variable with angular.toJson before sending it to a rest service - the toJson method transforms the newTest variable, even if it's not accessible on the instance during compile, and this makes the rest service not accept the json since it has properties that shouldn't be there.

推荐答案

TS 2.1具有对象扩展和休整功能,因此现在可以:

TS 2.1 has Object Spread and Rest, so it is possible now:

var my: MyTest = {test: "hello", newTest: "world"}

var { test, ...reduced } = my;

之后,简化后的内容将包含除"test"以外的所有属性.

After that reduced will contain all properties except of "test".

这篇关于如何减少JavaScript对象以仅包含接口中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆