在开发过程中,也可以使用泛型对类进行约束。

    1. class UserList<T> {
    2. private _userList: T[] = [];
    3. public get userList(): T[] {
    4. return this._userList;
    5. }
    6. public set userList(value: T[]) {
    7. this._userList = value;
    8. }
    9. public insert(info: T) {
    10. this._userList.push(info);
    11. }
    12. public shift(): T {
    13. return this._userList.shift() as T;
    14. }
    15. }

    上面代码中定义了一个类,通过这个类可以向其中存入一个完整的数组,也可以存入单个的用户名。

    接下来通过接口来当做类型。

    1. interface UserInterface {
    2. username: string,
    3. email: string
    4. }
    5. const list = new UserList<UserInterface>();
    6. list.userList = [{username: 'root', email: 'root@example.com'}, {username: 'admin', email: 'admin@example.com'}];
    7. console.log(list.userList)
    8. list.insert({username: 'xiaoming', email: 'xiaoming@example.com'});
    9. console.log(list.shift());