使用 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)和/或命名约定的语义(例如 IMyInterface
或 MyInterface
) 并允许您进行模拟和单元测试
关于javascript - 如何减少javascript对象只包含接口(interface)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31829951/