typescript类与接口:

74 阅读3分钟

四、类与接口:

  1. interface:

    interface User {
      name: string;
    }
    ​
    interface User {
      age: number;
    }
    ​
    const xgh: User = {
      name: "typescript",
      age: 20,
    };
    
    // 接口继承
    interface Member {
      name: string;
    }
    ​
    interface User extends Member {
      age: number;
    }
    ​
    class Person implements User {
      age: number = 23;
      name: string = "typescript";
    }
    
    // type 合并
    type Age = {
      age: number;
    };
    type Name = {
      name: string;
    };
    ​
    type User = Name & Age;
    const hd: User = { name: "typescript", age: 20 };
    ​
    type User = Name | Age;
    const hd: User = { name: "typescript" };
    
  2. type 与 interface 的差异对比:

    type 使用不允许重复声明的,但是interface是可以的;

    type 可以合并,interface可以继承;

  3. 类修饰符:

    // public:公共的
    class User {
      public name: string;
      public age: number;
      constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }
      public info(): string {
        return `${this.name}的年龄是${this.age}。`;
      }
    }
    ​
    const object = new User("typescript", 20);
    console.log(object.info()); // typescript的年龄是20。
    
    // protected: 受保护的,只能在 自身和子类访问
    // 自身
    class User {
      public name: string;
      protected age: number;    // 受保护的属性
      constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
      }
      public info(): string {
        return `${this.name}的年龄是${this.age}。`;
      }
    }
    ​
    const object = new User("typescript", 20);
    console.log(object.info()); // typescript的年龄是20。// 继承
    class Person {
      protected age: number;    // 受保护的属性
      constructor(age: number) {
        this.age = age;
      }
    }
    ​
    class User extends Person {
      public name: string;
      constructor(name: string, age: number) {
        super(age);
        this.name = name;
      }
      public info(): string {
        return `${this.name}的年龄是${this.age}。`;
      }
    }
    ​
    const object = new User("typescript", 20);
    console.log(object.info()); //typescript的年龄是20。
    
    // private:私有属性,外部不能访问,只在类内部访问
    class User {
      public name: string;
      private age: number;  // 私有的属性
      constructor(name: string, age: number) {
        this.age = age;
        this.name = name;
      }
      public info(): string {
        return `${this.name}的年龄是${this.age}。`;
      }
    }
    ​
    const object = new User("typescript", 20);
    console.log(object.info()); //typescript的年龄是20。
    
  4. readonly使用:

    class Axios {
      readonly site: string = "http://localhost:8080/api";
      constructor(site?: string) {
        this.site = site || this.site;
      }
      public get(url: string): any[] {
        console.log(`你请求的是${this.site}/${url}`);
        return [];
      }
    }
    ​
    const instance = new Axios("http://yaho.com/api");
    console.log(instance.get("user"));
    ​
    
  5. 单例模式:

    // 单例模式:饿汉式
    class Axios {
        private static instance = new Axios();
        private constructor() {}
        static make(): Axios {
            return Axios.instance;
        }
    }
    ​
    const instance1 = Axios.make();
    const instance2 = Axios.make();
    console.log(instance1 == instance2);
    
    // 单例模式:懒汉式
    class Axios {
        private static instance: Axios | null = null;
        private constructor() {}
        static make(): Axios {
            if (Axios.instance == null) {
                Axios.instance = new Axios();
            }
            return Axios.instance;
        }
    }
    ​
    const instance1 = Axios.make();
    const instance2 = Axios.make();
    console.log(instance1 == instance2);
    
  6. 访问器get 和 set:

    class User {
        private _name: string;
        constructor(name: string) {
            this._name = name;
        }
        public get name(): string {
            return this._name;
        }
        public set name(name: string) {
            this._name = name;
        }
    }
    const user = new User("mary");
    console.log(user.name); // mary
    user.name = "Jack";
    console.log(user.name); // Jack
    
    class Article {
        private _lists: any[] = [];
        constructor(lists: any[]) {
            this._lists = lists;
        }
        public get name(): any[] {
            return this._lists.map((article) => {
                article.title = article.title.substr(0, 2);
                return article;
            });
        }
        public set name(name: any[]) {
            this._lists = name;
        }
    }
    ​
    const article = new Article([
        { title: "typescript" },
        { title: "javascript" },
        { title: "angular" },
    ]);
    console.log(article.name); // [ { title: 'ty' }, { title: 'ja' }, { title: 'an' } ]
    
  7. 抽象类(abstract):

    抽象类不能new

    abstract class Animation {
        abstract move(): void;
        abstract name: string;
        protected getPos(): { x: number; y: number } {
            return { x: 100, y: 300 };
        }
    }
    class Tank extends Animation {
        name: string = "敌方";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }
    }
    class Player extends Animation {
        name: string = "玩家";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }
    }
    const tank = new Tank();
    const play = new Player();
    tank.move();
    play.move();
    
  8. 接口(interface):

    interface 与 abstract

    interface AnimationInterface {
        move(): void;
        name: string;
    }
    abstract class Animation {
        protected getPos(): { x: number; y: number } {
            return { x: 100, y: 300 };
        }
    }
    class Tank extends Animation implements AnimationInterface {
        name: string = "敌方";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }
    }
    class Player extends Animation implements AnimationInterface {
        name: string = "玩家";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }
    }
    const tank = new Tank();
    const play = new Player();
    tank.move();
    play.move();
    

    使用接口约束Typescript 对象

    interface UserInterface {
        name: string;
        age: number;
        info(): string;
    }
    ​
    let obj: UserInterface = {
        name: "John",
        age: 30,
        info() {
            return `${this.name}的年龄是${this.age}`;
        },
    };
    ​
    console.log(obj);
    
    // [key: string]: any;
    interface UserInterface {
        name: string;
        age: number;
        info(): string;
        [key: string]: any;
      }
    ​
      let obj: UserInterface = {
        name: "John",
        age: 30,
        info() {
          return `${this.name}的年龄是${this.age}`;
        },
        sex: "女",
      };
    ​
      console.log(obj);
    

    接口的继承:

    interface PlayEndInterface {
        end(): void;
    }
    interface AnimationInterface extends PlayEndInterface {
        move(): void;
        name: string;
    }
    abstract class Animation {
        protected getPos(): { x: number; y: number } {
            return { x: 100, y: 300 };
        }
    }
    class Tank extends Animation implements AnimationInterface {
        name: string = "敌方";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }
        end() {
            console.log('游戏结束');
    ​
        }
    }
    class Player extends Animation implements AnimationInterface {
        name: string = "玩家";
        public move(): void {
            console.log(`${this.name}坦克移动`);
        }a
        end(){
            console.log('游戏结束');
    ​
        }
    }
    const tank = new Tank();
    const play = new Player();
    tank.move();
    play.move();
    tank.end();
    

    使用接口对Typescript类型约束:

    interface UserInterface {
        name: string;
        age: number;
        isLock: boolean;
    }
    ​
    const user: UserInterface ={
        name: "typescript",
        age: 30,
        isLock: false
    }
    ​
    function isLock(user: UserInterface, lock: boolean): UserInterface {
        user.isLock = lock
        return user
    }
    console.log(isLock(user, true));    // { name: 'typescript', age: 30, isLock: true }
    

    使用接口约束类:

    interface UserInterface{
        name: string
        age: number
    }
    class User {
        _info: UserInterface
        constructor(info: UserInterface) {
            this._info = info 
        }
    ​
        get info(): UserInterface {
            return this._info
        }
    }
    ​
    const user = new User({name:"typescript", age: 23})
    console.log(user.info); //{ name: 'typescript', age: 23 }
    

    数组中使用接口:

    enum SexType{
        Boy,
        Girl
    }
    interface UserInterface {
        name: string;
        age: number;
        sex: SexType
    }
    
    const user1: UserInterface = {
        name: "John",
        age: 20,
        sex: SexType.Girl
    
    };
    const user2: UserInterface = {
        name: "Mary",
        age: 30,
        sex: SexType.Boy
    };
    
    const userList: UserInterface[] = [user1, user2];
    console.log(userList);    // [ { name: 'John', age: 20, sex: 1 }, { name: 'Mary', age: 30, sex: 0 } ]
    

    接口声明合并:

    看到下面的代码,大多数人会认为第二个接口会覆盖第一个接口,但其实不是这样的;它们之间发生了合并而并非覆盖

    interface AnimationInterface {
        name: string;
        move():void
    }
    ​
    interface AnimationInterface{
        end():void
    }
    ​
    class Player implements AnimationInterface{
        constructor(name:string) {
            this.name = name;
        }
        name: string;
        end(): void {
            throw new Error("Method not implemented.");
        }
        move(): void {
            console.log('移动了');
    ​
        }
    }
    ​
    const play = new Player('John')
    console.log(play);  // Player { name: 'John' }
  9. type使用:

    type语法:

    type User = {
        name: string,
        age: number,
        show(): string
    }
    ​
    const user: User = {  name: 'John', age: 12, show: () => { return 'John'; }}
    

    联合类型:

    type IsAdmin = boolean;
    type Sex = 'boy' | 'girl';
    ​
    type User = {
        name: string,
        age: number,
        isAdmin: IsAdmin,
        sex: Sex
    }
    ​
    const user: User = {  name: 'John', age: 12, isAdmin: true, sex: 'girl'}