javascript - 通过扩展对象文字来实例化 Typescript 变量

标签 javascript typescript underscore.js lodash

假设我有两个接口(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/

相关文章:

javascript - 王牌编辑器 : Determine if mode exists

javascript - 如何在网络应用程序上显示未知数量的图像?

typescript - 类型不提供与使用 withStyles 的签名的匹配

javascript - jquery上下文菜单禁用输入

javascript - 如何将函数处理程序从 Controller 传递到 AngularJs 中的指令隔离范围?

node.js - Web3js 无法在 Azure 上编译

typescript - 为什么我需要在 Typescript 中输入 cast?

javascript - Underscore.js数组过滤

javascript - 如何在 JavaScript 中连接两个具有数组属性的对象?

javascript - 无法让 .siblings() 在 jQuery 中工作