wanghy6503
7/16/2019 - 8:33 AM

Typescript Generics Example

interface Bookmark {
    id: string;
}
class BookmarksService {
    items: Bookmark[] = [];
}

class BookmarksService<T> {
    items: T[] = [];
}

class BookmarksService<T extends Bookmark> {
    items: T[] = [];
}

class SearchPageComponent {
    movie: Movie;
    constructor(private bs: BookmarksService<Movie>) {}
    getFirstMovie() {
        this.movie = this.bs.items[0]; // 👍
    }
    getSecondMovie() {
        this.movie = this.bs.items[1]; // 👍
    }
}

class BookmarksService<T extends Bookmark = Bookmark> {
    items: T[] = [];
}
const bs = new BookmarksService();
// I don't have to provide the type for the generic now
// - in that case 'bs' will be of that default type 'Bookmark'