TypeScript中的类和创建对象的数组

时间:2018-12-18 04:38:51

标签: javascript reactjs typescript

我有一个这样的类,需要创建一个属性集合。在C#中,我可以使用列表或任何集合类型,但如何在打字稿中使用它。

class Movies implements Imovies{


    public Id : string;
    public get fid(): string {
        return this.Id;
    }
    public set fid(theid:string) {
        this.Id=theid;
    }

    public dailyrentalRate : number;
    public get fdailyrentalRate(): number {
        return this.dailyrentalRate;
    }
    public set fdailyrentalRate(theid:number) {
        this.dailyrentalRate=theid;
    }

    public numberinstock : number;
    public get fnumberinstock(): number {
        return this.numberinstock;
    }
    public set fnumberinstock(theid:number) {
        this.numberinstock=theid;
    }

    public publishDate : string;
    public get fpublishDate(): string {
        return this.publishDate;
    }
    public set fpublishDate(theid:string) {
        this.publishDate=theid;
    }

    public title : string;
    public get ftitle(): string {
        return this.title;
    }
    public set ftitle(theid:string) {
        this.title=theid;
    }
}

我尝试如下将值插入数组

let mov=new Array<Movies>();

mov[0].fid="asdasd";
mov[0].fdailyrentalRate=2;
mov[0].fnumberinstock=5;
mov[0].fpublishDate="2018-05-23";
mov[0].ftitle="name";

mov[1].fid="asdasda";
mov[1].fdailyrentalRate=32;
mov[1].fnumberinstock=35;
mov[1].fpublishDate="2018-06-23";
mov[1].ftitle="name2";

但显示错误

TypeError:无法设置未定义的属性“ fid”

1 个答案:

答案 0 :(得分:0)

您还可以使用构造函数实现Movie类,然后创建一个Movie数组,如下所示:

const movies: Movie[] = [];

在您可以将电影对象推入电影数组之后:

const movie = new Movie();
movie.fid="test1"; 
movie.dailyrentalRate=2; 
movie.numberinstock=5; 
movie.publishDate="2018-05-23"; 
movie.title="name";     
movies.push(movie);

您可以在此处看到一个有效的示例:https://stackblitz.com/edit/typescript-array-movies