假设我有两个接口(interface),我想用它们构造一个实例。其中一个接口(interface)扩展了另一个接口(interface)。
interface IScope {/*... */}
interface IDialogScope extends IScope { a? : string , b? : string }
假设第三方模块中有一个方法可以让我实例化 IScope 类型的变量
var scope : IDialogScope = ScopeBuilder.build(); /* build actually returns an IScope type */
现在我可以填充范围变量
scope.a = "hello"; scope.b = "world";
如果我使用 lodash/underscore,我可以使用自定义属性扩展现有对象文字并获得最终对象。这里 TypeScript 的问题是,我不能只创建一个实现 IDialogScope 的 DialogScope 类,因为那样我还必须实现 IScope 中的所有内容,而我不能这样做,因为它来自第三方库。
我希望能够在 TypeScript 中执行此操作:
var scope : IDialogScope = _.extend({}, ScopeBuilder.build(), {a: "hello", b: "world"});
最佳答案
I want to be able to do this in TypeScript:
这正是交叉点类型的用途。
function extend<T, U>(first: T, second: U): T & U {
let result = <T & U> {};
for (let id in first) {
result[id] = first[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result[id] = second[id];
}
}
return result;
}
var x = extend({ a: "hello" }, { b: 42 });
var s = x.a;
var n = x.b;
这些最近才发布:https://github.com/Microsoft/TypeScript/pull/3622
它将成为 TypeScript 1.6 的一部分。
如果你今天想使用它,你可以使用ntypescript
:https://github.com/basarat/ntypescript
关于javascript - 通过扩展对象文字来实例化 Typescript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254757/