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

标签 javascript typescript

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

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

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

我已经尝试将以下内容作为 Typescript 的等价物,根据需要插入到 export classconstructor() 之间,但它不喜欢 '.':

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

最佳答案

对于您所描述的内容,这是一个等效的 typescript :

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)中描述:

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

然后,正如您在评论中所说,如果您有一个 View ,您可以像这样将其添加为属性:

class MyView {
    mediaItem = new MediaItem()
}

或者如果您正在使用一个接口(interface):

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

关于javascript - 将 Javascript 成员变量转换为 Typescript 成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37976035/

相关文章:

javascript - 为什么这个原型(prototype)代码会这样工作?

javascript - 在循环中替换数组中的值

javascript - 当我点击一个新对象时忘记了之前的点击?

javascript - Angular 8 解析器未解析

typescript - 在 Backbone.js 中使用 Collection.model 属性

javascript - JQuery 没有得到正确的宽度

typescript - 接口(interface)类型推断

Angular 2从文件下载中获取文件名

javascript - 未找到 Angular 返回路线上的 Jasmine 单元测试

javascript - 保护 JavaScript 源代码