[英]Converting Javascript member variable to Typescript member variable
我正在尝试找出如何将Javascript代码的成员变量转换为Typescript等效项。
在我的Javascript代码中,在constructor()
之后,我有:
this.theMediaItem = [];
this.theMediaItem.embedLink = '';
this.theMediaItem.username = '';
我已经尝试了以下内容作为Typescript等效项,并根据需要将其插入了export class
和constructor()
但它不喜欢'。':
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() {
// ...
}
}
您尝试过“词典”模式吗? 请参考下面的TS文档和Wiki页面。
接口Dictionary {[index:string]:string; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.