【问题标题】:Instantiating Typescript variable by extending object literals通过扩展对象字面量来实例化 Typescript 变量
【发布时间】:2015-07-06 20:12:25
【问题描述】:

假设我有两个接口,我想从中构造一个实例。其中一个接口扩展了另一个接口。

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"});

【问题讨论】:

    标签: javascript typescript underscore.js lodash


    【解决方案1】:

    我希望能够在 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

    【讨论】:

      猜你喜欢
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多