簡體   English   中英

將Javascript成員變量轉換為Typescript成員變量

[英]Converting Javascript member variable to Typescript member variable

我正在嘗試找出如何將Javascript代碼的成員變量轉換為Typescript等效項。

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

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

我已經嘗試了以下內容作為Typescript等效項,並根據需要將其插入了export classconstructor()但它不喜歡'。':

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

對於您要描述的內容,這里有一個等效的打字稿:

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

您需要使用以下語法,還請確保不要將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

您嘗試過“詞典”模式嗎? 請參考下面的TS文檔和Wiki頁面。

接口Dictionary {[index:string]:string; }

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM