zoukankan      html  css  js  c++  java
  • 接口

    属性检查

    1. 类接口带有几个确定的属性,同时还会带有其他不确定的属性时,可如下定义:
    interface SquareConfig {
      color?: string
      width?: number
      [propName: string]: any
    }
    
    1. 使用类型断言(as)跳过检查
    let mySquare = createSquare({  100, opacity: 0.5 } as SquareConfig)
    

    可索引的类型

    interface StringArray {
      [index: number]: string
    }
    
    let myArray: StringArray
    myArray = ['Bob', 'Fred']
    
    let myStr: string = myArray[0]
    

    这个索引签名表示了当用 number 去索引 StringArray 时会得到 string 类型的返回值。

    函数类型

    interface SearchFunc {
      (source: string, subString: string): boolean;
      func1(arg1: string, arg2: any): void;
      func2(arg1: number, arg2?: boolean): number;
    }
    

    类类型

    实现接口

    接口描述了类的公共部分,而不是公共和私有两部分。

    interface ClockInterface {
      currentTime: Date
      setTime(d: Date)
    }
    
    class Clock implements ClockInterface {
      currentTime: Date
      setTime(d: Date) {
        this.currentTime = d
      }
      constructor(h: number, m: number) { }
    }
    

    类静态部分与实例部分

    interface ClockConstructor {
      new (hour: number, minute: number): ClockInterface
    }
    interface ClockInterface {
      tick()
    }
    
    function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
      return new ctor(hour, minute)
    }
    
    class DigitalClock implements ClockInterface {
      constructor(h: number, m: number) { }
      tick() {
        console.log('beep beep')
      }
    }
    class AnalogClock implements ClockInterface {
      constructor(h: number, m: number) { }
      tick() {
        console.log('tick tock')
      }
    }
    
    let digital = createClock(DigitalClock, 12, 17)
    let analog = createClock(AnalogClock, 7, 32)
    

    createClock 的第一个参数是 ClockConstructor 类型,在 createClock(AnalogClock, 7, 32) 里,会检查 AnalogClock 是否符合构造函数签名。

    继承接口

    interface Shape {
      color: string
    }
    
    interface PenStroke {
      penWidth: number
    }
    
    interface myColor extends Shape {
        fontSize: number
    }
    
    interface Square extends Shape, PenStroke {
      sideLength: number
    }
    
    let square = {} as Square
    square.color = 'blue'
    square.sideLength = 10
    square.penWidth = 5.0
    
  • 相关阅读:
    实现个人域名跳转指定网站
    Latex数学符号表
    Python—Matplotlib基础学习
    Python—Pandas基础学习
    Python—Numpy基础学习
    程序员必读的计算机书籍(附资源分享)
    嗷嗷
    CTF之misc
    网安基础思维导图
    NAT、动态路由及实验
  • 原文地址:https://www.cnblogs.com/renzhiwei2017/p/15533109.html
Copyright © 2011-2022 走看看