将Javascript成员变量转换为Typescript成员变量

时间:2016-06-22 18:47:34

标签: javascript typescript

我正在尝试研究如何将我的Javascript代码的成员变量转换为Typescript等价物。

在我的Javascript代码中,在我constructor()之后:

this.theMediaItem = [];
this.theMediaItem.embedLink = '';
this.theMediaItem.username = '';

我尝试了以下作为Typescript等效项,根据需要在export classconstructor()之间插入,但它不喜欢&#39;。&#39;:< / p>

theMediaItem = [];
theMediaItem.embedLink = '';
theMediaItem.username = '';

3 个答案:

答案 0 :(得分:4)

对于你所描述的内容,这里有一个等效的打字稿:

interface MediaItemArray<T> extends Array<T> {
    embedLink?: string;
    username?: string;
}

class MyClass {
    theMediaItem: MediaItemArray<any> = [];

    constructor() {
        this.theMediaItem.embedLink = "";
        this.theMediaItem.username = "";
    }
}

虽然这有点奇怪......你可能不想使用数组,最好只在类上直接获得属性:

class MediaItem {
    embedLink = "";
    username = "";
}

或在界面中描述:

interface MediaItem {
    embedLink: string;
    username: string;
}

然后,正如您在评论中所说,如果您有一个视图,您可以将其添加为属性,如下所示:

class MyView {
    mediaItem = new MediaItem()
}

或者如果您使用的是界面:

class MyView {
    mediaItem: MediaItem = {
        embedLink: "",
        username: ""
    };
}

答案 1 :(得分:2)

您需要使用下面的语法,同时确保您没有将theMediaItem定义为数组,因为从使用情况来看,我看到您分配了它的属性:

class YourClass {
    constructor() {
       this.theMediaItem = {};
       this.theMediaItem.embedLink = '';
       this.theMediaItem.username = '';
    }
}

或以简单的方式做到:

class YourClass {
    theMediaItem = { embedLink: '', username: '' },    
    constructor() {
       // ...
    }
}

https://www.typescriptlang.org/docs/tutorial.html

答案 2 :(得分:1)

您是否尝试过该词典&#39;图案? 请参阅下面的TS文档和维基页面。

interface Dictionary {[index:string]:string; }

https://typescript.codeplex.com/wikipage?title=Interfaces%20in%20TypeScript&referringTitle=TypeScript%20Documentation

https://en.wikipedia.org/wiki/Associative_array#Example

相关问题