简体   繁体   English

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

[英]Instantiating Typescript variable by extending object literals

Let's say I have two interfaces by which I want to construct an instance out of. 假设我有两个要用来构造实例的接口。 One of the interfaces extends the other. 其中一个接口扩展了另一个接口。

interface IScope {/*... */}

interface IDialogScope extends IScope { a? : string , b? : string }

Let's say that there is a method in a third party module that let's me instantiate a variable of type IScope 假设第三方模块中有一个方法可以让我实例化IScope类型的变量

var scope : IDialogScope = ScopeBuilder.build(); /* build actually returns an IScope type */

Now I can populate the scope variable 现在我可以填充范围变量

scope.a = "hello"; scope.b = "world";

If I were using lodash/underscore, I could have just extended an existing object literal with my custom properties and gotten my final object. 如果我使用lodash / underscore,则可以使用自定义属性扩展现有的对象文字,并获得最终的对象。 The problem with TypeScript here is that I can't just create a DialogScope class that implements IDialogScope because then I would also have to implement everything in IScope which I can't because it's from a third party library. TypeScript的问题在于,我不能只创建实现IDialogScope的DialogScope类,因为那样我还必须实现IScope中的所有内容,因为它来自第三方库,所以我不能实现。

I want to be able to do this in TypeScript: 我希望能够在TypeScript中做到这一点:

var scope : IDialogScope = _.extend({}, ScopeBuilder.build(), {a: "hello", b: "world"});

I want to be able to do this in TypeScript: 我希望能够在TypeScript中做到这一点:

This is exactly what intersection types are for. 这正是相交类型的用途。

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;

These were only released recently : https://github.com/Microsoft/TypeScript/pull/3622 这些只是最近才发布的: https : //github.com/Microsoft/TypeScript/pull/3622

It will be a part of TypeScript 1.6. 它将是TypeScript 1.6的一部分。

If you want to use it today you can use ntypescript : https://github.com/basarat/ntypescript 如果今天想使用它,可以使用ntypescripthttps : //github.com/basarat/ntypescript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM