zoukankan      html  css  js  c++  java
  • 接口(interface)

    作用

    在编译期间,能够对值的数据结构进行检查。可以自定义类型。

    用法

    接口内部写法

    属性

    接口中的属性分为:必需属性,可选属性,只读属性,额外属性

    interface Person{
        readonly id: number, //只读属性 (不允许修改)
        name: string, //必需属性
        sex?: number,  //可选属性
        [key: string]: any //额外属性 
    }
    

    let person:Person = {id: 1, name: "蜡笔小新", hobby: "superman"};
    person.id = 3453; //会提示只读属性不能修改


    类型

    1. 函数类型,主要定义参数列表和返回值
    2. 可索引类型,具有一个索引签名;索引签名分为:数字和字符串。数字是字符串的子类型(因为在编译的时候,数字会被转化为字符串)

      //函数类型的接口  (只定义参数列表和返回类型)
      interface SearchFunc {
          (source: string, subString: string): boolean;
      }
      

      let mySearch: SearchFunc;
      mySearch = function (sour: string, sub: string) {
      let result = sour.search(sub);
      return result > -1;
      }

      interface StringArray {
      [index: number]: string; //索引类型
      length: number;
      }
      let myArray: StringArray;
      myArray = ["4654","wfwf","wfewefewf"];
      let str: string = myArray[0];

    接口在类、接口中的使用

    在类中,

    类实现接口,接口只描述了类的公共部分。
    一个类在实现一个接口时,只对实例部分进行类型检查。

        interface PersonInterface {
            say():void;
            //[key: string]: any;
        }
        class Student implements PersonInterface {
            name: string;
            constructor(name: string){
                this.name = name;
            }
            say() {
                console.log("Hi,"+ this.name);
            }
        }
        let student = new Student("傻白");
    

    补充概念
    类静态部分 & 实例部分 
    静态部分: contrutor 函数 
    实例部分

    在接口中,

    接口与接口之间也可以相互继承:extends

    interface Shape {
        color: string;
    }
    interface PenStroke {
        PenWidth: number;
    }
    interface Square extends Shape, PenStroke {
        sideLength: number;
    }
    

    let square = <Square>{color: "df", PenWidth: 346346,sideLength: 45654};

    接口继承类

    只继承类的成员但不包括其实现。如果这个类刚好有private和protected成员,按要实现这个接口的类一定是子类。

    class Control {
        state: any;
        private type: string;
    }
    

    interface SelectableControl extends Control {
    select() : void;
    }

    class Button extends Control implements SelectableControl {
    select() {
    console.log(this.state);
    }
    constructor(state: string) {
    super();
    this.state = state;
    }
    }

    let button = new Button("按钮");
    console.dir(button);

  • 相关阅读:
    spring配置初始化出错
    Java常用工具类(计算MD5,验证码随机生成,天数差值计算)
    Java基础(静态static)
    websocket使用nginx代理后连接频繁打开和关闭
    关于kafka客户端版本与服务端版本不一致导致的一次坑
    kafka
    maven常用命令含义
    pg数据库org.postgresql.util.PSQLException: ERROR: "xxx" is not a sequence
    @Param注解和@Mapper注解
    springmvc对参数接收的两个注解@RequestParam和@RequestBody
  • 原文地址:https://www.cnblogs.com/zxn-114477/p/15010781.html
Copyright © 2011-2022 走看看