最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Error TS1112: A class member cannot be declared optional - Stack Overflow

programmeradmin6浏览0评论

I am trying to build a movie catalog using Angular and ionic. The movie class contains id, title, image and plot.

In the first page, the app displays only id title & image. It omits plot.

Movie class

export class Movie{
    id: number;
    title: string;
    img: string;
    plot?: string;
}

In the main typescript file, I am assigning the movie details as follows

export class MainPage implements OnInit{

    movies: Movie[];
    getMovies(){
        this.movies = [{id: 1, title: 'test', img: 'img1'}]
    }
    ngOnInit(){
        this.getMovies();
    }
}

But this returns following error

Error TS1112: A class member cannot be declared optional. It is referring to the 'plot' variable.

How can I achieve what I intended to? Is there any other options?

Thanks in advance for your help!

I am trying to build a movie catalog using Angular and ionic. The movie class contains id, title, image and plot.

In the first page, the app displays only id title & image. It omits plot.

Movie class

export class Movie{
    id: number;
    title: string;
    img: string;
    plot?: string;
}

In the main typescript file, I am assigning the movie details as follows

export class MainPage implements OnInit{

    movies: Movie[];
    getMovies(){
        this.movies = [{id: 1, title: 'test', img: 'img1'}]
    }
    ngOnInit(){
        this.getMovies();
    }
}

But this returns following error

Error TS1112: A class member cannot be declared optional. It is referring to the 'plot' variable.

How can I achieve what I intended to? Is there any other options?

Thanks in advance for your help!

Share Improve this question asked Jul 22, 2016 at 10:50 Vyas RaoVyas Rao 4986 gold badges10 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

If Movie is just defining a data structure and doesn't contain any implementation code, then just change it to an Interface:

interface Movie{
    id: number;
    title: string;
    img: string;
    plot?: string;
}

Alternatively the class can just define plot without the ? However in this case you will need to set plot to null in your getMoves method:

class Movie{
    id: number;
    title: string;
    img: string;
    plot: string;
}

class MainPage {

    movies: Movie[];
    getMovies(){
        this.movies = [{id: 1, title: 'test', img: 'img1', plot: null}]
    }
    ngOnInit(){
        this.getMovies();
    }
}
发布评论

评论列表(0)

  1. 暂无评论