美文网首页
typescript 入门-接口

typescript 入门-接口

作者: copyLeft | 来源:发表于2021-06-09 09:39 被阅读0次

    interface 定义

    interface i_Tree{
      leftLeaf: string
      rightLeaf: string
    }
    // 作为类型定义
    const tree: i_Tree = {
      leftLeaf: 'left',
      rightLeaf: 'right'
    }
    

    可选属性

    interface Man{
       name: string // 必选
       job?: string // 可选
    }
    

    只读

    interface Man{
      readonly sex:string
      name: string
      job?: string
    }
    

    函数描述

    interface i_talk{
      (msg:string): void;
    }
    const talk:i_talk = (msg: string) => {
      console.log(msg)
    }
    

    可索引

    interface i_list{
      [index: number]: string
    }
    const li: i_list = ['ni', 'mi']
    

    类描述

    interface i_Man{
      name: string
    }
    
    
    class Man implements i_Man{
      name:string
      constructor(name: string) {
        this.name = name
      }
    }
    
    
    
    
    const c = new Man('cc')
    console.log(c.name)
    

    类构造器描述

    interface i_Man{
      name: string
    }
    
    
    class Man implements i_Man{
      name:string
      constructor(name: string) {
        this.name = name
      }
    }
    
    
    // 定义构造函数接口
    interface i_ManConstructor{
      new (name:string): i_Man
    }
    
    
    // 接收类定义作为参数
    function createMan(c: i_ManConstructor, name: string):i_Man{
      return new c(name)
    }
    

    混合类型

    interface i_talk{
      (msg?: string): void
      defaultMsg?: string
    }
    
    
    
    
    const talk: i_talk = function (msg?: string): void{
      console.log(msg || talk.defaultMsg)
    }
    
    
    
    
    talk.defaultMsg = 'not find msg'
    talk()
    // 函数也是对象,可以拥有自己的属性
    

    继承接口

    interface i_A{
      propA: string
    }
    
    
    interface i_B{
      propB: string
    }
    
    
    interface i_C extends i_A, i_B{
      propC: string
    }
    
    
    const c: i_C = {
      propA: 'a',
      propB: 'b',
      propC: 'c',
    } 
    

    继承类

    class Control {
        private state: any;
    }
    
    
    interface SelectableControl extends Control {
        select(): void;
    }
    
    
    class Button extends Control implements SelectableControl {
        select() { }
    }
    
    
    class TextBox extends Control {
        select() { }
    }
    
    
    // 错误:“Image”类型缺少“state”属性。
    class Image implements SelectableControl {
        select() { }
    }
    
    
    class Location {}
    

    相关文章

      网友评论

          本文标题:typescript 入门-接口

          本文链接:https://www.haomeiwen.com/subject/qeoseltx.html