javascript - 如何减少javascript对象只包含接口(interface)的属性

标签 javascript angularjs typescript

使用 typescript 时,声明的接口(interface)可能如下所示:

interface MyInterface {
  test: string;
}

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

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

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

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

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

问题

一般来说,如何使“简化”变量仅包含“MyInterface”接口(interface)中声明的属性。

为什么

在将“reduced”变量发送到休息服务之前尝试将“reduced”变量与 angular.toJson 一起使用时会出现问题 - toJson 方法会转换 newTest 变量,即使它在编译期间无法在实例上访问,这使得休息服务不接受 json,因为它具有不应该存在的属性。

最佳答案

这是不可能的。 interface 的原因是 Typescript 构造和 transpiled JS code是空的

//this code transpiles to empty!
interface MyInterface {
  test: string;
}

因此在运行时没有任何东西可以“使用”——没有属性可以查询。

@jamesmoey 的回答解释了实现预期结果的解决方法。 我使用的一个类似的解决方案是简单地将“接口(interface)”定义为一个类——

class MyInterface {
  test: string = undefined;
}

然后您可以使用 lodash 从“接口(interface)”中选择属性以注入(inject)到您的对象中:

import _ from 'lodash';  //npm i lodash

const before = { test: "hello", newTest: "world"};
let reduced = new MyInterface();
_.assign(reduced , _.pick(before, _.keys(reduced)));
console.log('reduced', reduced)//contains only 'test' property

参见 JSFiddle

这是一个实用的解决方案,它对我很有帮助,而不会陷入关于它是否真的是一个接口(interface)和/或命名约定的语义(例如 IMyInterfaceMyInterface ) 并允许您进行模拟和单元测试

关于javascript - 如何减少javascript对象只包含接口(interface)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31829951/

相关文章:

node.js - typescript :req.user 可能是 'undefined' - express 和 passport js

javascript - CKEditor 通过 js 启用/禁用按钮

javascript - 更正可拖动元素的像素位置以从任意 Angular 开始

Javascript - 按模式将字符串拆分/划分为 N 个部分的简单方法,其中最后一部分是字符串的其余部分

javascript - 如何在一个指令中进行变量更改以反射(reflect)在另一个指令中

javascript - 根据另一个类的属性创建一个带有 getter 的类

Angular |将服务注入(inject)装饰器

AJAX 成功函数上的 Javascript/AJAX 当前输入

javascript - typescript , Angular 1.x : How do lambda functions affect property resolution?

javascript - Angular 获取 Json 值