zoukankan      html  css  js  c++  java
  • Typescript

    原文:TypeScript基本知识点整理

    零、序:

      接口定义:接口是对传入参数进行约束;或者对类里面的属性和方法进行声明和约束,实现这个接口的类必须实现该接口里面属性和方法;typescript中的接口用interface关键字定义。

      接口作用:接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部状态数据,也不关心这些类里方法的实现细节,它只规定这批类里必须提供某些方法,提供这些方法的类就可以满足实际需要。typescrip中的接口类似于java,同时还增加了更灵活的接口类型,包括属性、函数、可索引和类等。
     

    一、属性接口

      对传入对象的约束,形式上很像 json 对象:

    interface Sx {
        name : string
        age : number
    }
    
    function f8(peop:Sx) {
        //name age 必须传递
        console.log(peop)
    }
    
    const obj = {
        name : 'liu',
        age : 25
    }
    f8(obj)
    

      注意

    1. 不允许添加接口中未定义的属性;

    二、函数类型的接口

      对方法传入的参数和返回值进行约束

    interface Sta {
        (difang: string, todo: string): string
    }
    
    let play: Sta = (difang: string, todo: string): string => {
        return `我们去${difang}吃${todo}`
    }
    
    console.log(play('灞桥', '吃烧烤'))
    

    三、可索引的接口

      对索引和传入的参数的约束

    //对数组的约束
    interface UserArr {
        //索引为number,参数为string
        [index: number]: string
    }
    
    const arr: UserArr = ['a', 'b']
    console.log(arr)
    
    //对 对象的约束
    interface UserObj {
        [index: number]: number
    }
    
    const obj1: UserObj = { 2:1, 3:4 }
    console.dir(obj1)
    

    四、类的类型约束

    interface Anmal {
        //对类里面的属性和方法进行约束
        name: string
        eat(food:string): void
    }
    // 类实现接口要用implements , 子类必须实现接口里面声明的属性和方法
    class Laoshu implements Anmal{
        name: string
        constructor(name: string) {
            this.name = name
        }
        eat(food:string): void {
            console.log(`${this.name}吃${food}`)
        }
    }
    const lao: Laoshu = new Laoshu('老鼠')
    lao.eat('粮食')
    

    五、接口继承

    interface Anmal {
      //对类里面的属性和方法进行约束
      name: string
      eat(food:string): void
    }
    //实现LaoHu的这个接口,必须也要实现LaoHu继承的Anmal接口中的方法
    interface LaoHu extends Anmal{
      say (sa : string) : void
    }
    //继承并实现接口
    class XiaoLaoHu implements LaoHu{
      name : string
      constructor (name : string) {
          this.name = name
      }
      eat (food : string) : void {
          console.log(`${this.name}吃${food}`)
      }
      say(sa: string): void {
          console.log(`${this.name}说${sa}`)
      }
    }
    
    const xiao : XiaoLaoHu = new XiaoLaoHu('老虎')
    xiao.eat('肉')
    xiao.say('你好')
    
  • 相关阅读:
    golang image库的使用
    http1.0/1.1/2.0/h2c/golang使用随笔
    3、逻辑回归 && 正则化
    1、Batch Normalization
    5、极大似然估计
    4、交叉熵与softmax
    2、卷积核,感受野
    Vue学习
    Qeios、github、overleaf、paperwithcode, 越来越多的web云端工具
    投稿遇到的arxiv论文引用问题的办法
  • 原文地址:https://www.cnblogs.com/cc-freiheit/p/10997889.html
Copyright © 2011-2022 走看看