[05] Basic knowledge: interface in typescript

1. The role of the interface

In object-oriented programming, an interface is a normative definition, which defines the norms of behavior and actions; in programming, an interface acts as a restriction and norm.

The interface defines the specifications that a certain batch of classes need to abide by. The interface does not care about the internal state data of these classes, nor does it care about the implementation details of the methods in these classes. It only stipulates that some methods must be provided in this batch of classes. Provide these The class of the method can meet the actual needs.

Interfaces in TypeScript are similar to Java, while adding more flexible interface types, including properties, functions, indexables, and classes.

Two, attribute type interface

1. Understand, function parameter type constraints

The parameter type constraints of functions in typescript can only take effect for a single function

// ts 中定义方法传入参数,约束类型必须为 string
function print(label: string): void {
    
    
  console.log(label)
}
print('hahah') // hahah

// ts 中定义方法传入参数,对 json 进行约束
function printObj(labelInfo: {
     
      label: string }): void {
    
    
  console.log(labelInfo.label)
}
printObj({
    
     label: 'hahah' }) // hahah

2. The attribute type interface restricts the quantity of method input parameters

The attribute interface is used to constrain the json and the incoming parameters of the batch method. Interfaces are defined with the interface keyword.

// 定义属性接口,对传入对象进行约束
interface FullName {
    
    
  firstName: string; // 注意,以 ; 结束,可省略 
  lastName: string
}

// 定义方法 getName
function getName(name: FullName): void {
    
    
  console.log(`${
      
      name.firstName}${
      
      name.lastName}`)
}
// 定义方法 returnName
function returnName(name: FullName): string {
    
    
  return `${
      
      name.firstName}${
      
      name.lastName}`
}

// 传入参数必须包含 firstName、lastName;参数的顺序可以不一样
getName({
    
     firstName: '林', lastName: '一'})
returnName({
    
     firstName: '佟', lastName: '年'})

3. Optional attributes of the attribute type interface

In typescript, optional attributes are defined in the form of [attribute name?: data type], which means that the attribute can not be passed in the current json object.

// 接口:可选属性
interface FullName {
    
    
  firstName?: string // 可选属性
  lastName: string
}

// 定义方法 getName
function getName(name: FullName): void {
    
    
  console.log(`${
      
      name.firstName}${
      
      name.lastName}`)
}

getName({
    
     lastName: '一'}) // undefined一

4. Attribute type interface case

jquery ajax request encapsulation, just for example

interface Config {
    
    
  type: string // 请求方式
  url: string // 请求地址
  data?: string // 请求参数
  dataType: string // 参数类型
}

function ajax(config: Config) {
    
    
  let xhr = new XMLHttpRequest()
  xhr.open(config.type, config.url, true)
  xhr.send(config.data)
  xhr.onreadystatechange = function() {
    
    
    if (xhr.readyState == 4 && xhr.status == 200) {
    
    
      if (config.dataType =='json') {
    
    
        console.log(JSON.parse(xhr.responseText))
      }
    }
  }
}

ajax({
    
    
  type: 'get',
  url: 'http://a.itying.com/api/productlist', // api
  data:'name=zhangsan',
  dataType: 'json'
})

3. Function type interface

Constrain the parameters passed in by the method and the return value

// 定义加密的函数类型接口
interface encrypt {
    
    
  (key: string, value: string): string
}

const md5: encrypt = function(key:string, value: string): string {
    
    
  // 模拟操作,加密算法
  return `${
      
      key}+${
      
      value}`
}

const sha1: encrypt = function(key:string, value: string): string {
    
    
  // 模拟操作,加密算法
  return `${
      
      key}-${
      
      value}`
}

console.log(md5('md5', '加密字符串')) // md5+加密字符串
console.log(sha1('sha1', '加密字符串')) // sha1-加密字符串

4. Indexable Type Interface

Constrain arrays and objects, not commonly used

1. Constraint array

// ts中定义数组
const arr: number[] = [1, 2]
const arr2: Array<string> = ['1', '2']

// 定义可索引类型接口
interface UseArr {
    
    
  // 索引值为number,value为string
  [index: number]: string
}

const arr3: UseArr = ['1', '2']

2. Constrained objects

interface UseObj {
    
    
  // 索引值为string,value为string
  [index: string]: string
}

const obj: UseObj = {
    
    
  name: 'lily',
  sex: '女'
}

Five, class type interface

The class type interface is used to constrain the class, similar to an abstract class. The interface is defined by the keyword interface, and the interface is realized by the keyword implements in the class.

// 定义 类类型接口(标准)
interface Animal {
    
    
  name: string
  eat(str: string): void
}

// 实现接口
class Dog implements Animal {
    
    
  public name: string
  constructor(name: string) {
    
    
    this.name = name
  }

  // 类中必须要有 eat 方法,没有 ts 编译保存;参数可以没有
  eat(str: string): void {
    
    
    console.log(`${
      
      this.name}${
      
      str}`)
  }
}

// 实例化 Dog 类
const dog = new Dog('小黑')
dog.eat('粮食') // 小黑吃粮食

6. Interface extension

Interfaces can inherit interfaces, which were previously inherited through the keyword extends.

interface Animal {
    
    
  eat(): void
}

// Person接口 继承 Animal接口
interface Person extends Animal {
    
    
  work(): void
}

// People类 使用 Person接口
class People implements Person {
    
    
  public name: string
  constructor(name: string) {
    
    
    this.name = name
  }

  eat(): void {
    
    
    console.log(this.name, 'People类必须有eat方法')
  }

  work(): void {
    
    
    console.log(this.name, 'People类必须有work方法')
  }
}

const people = new People('某个人')
people.eat() // 某个人 People类必须有eat方法
people.work() // 某个人 People类必须有work方法

Complex application example, the class inherits the parent class and implements the interface

interface Animal {
    
    
  eat(): void
}

interface Person extends Animal {
    
    
  work(): void
}

class Programmer {
    
    
  public name: string
  constructor(name: string) {
    
    
    this.name = name
  }
  coding(code: string): void {
    
    
    console.log(this.name + code)
  }
}

// People类 继承Programmer类  使用Person接口
class People extends Programmer implements Person {
    
    
  constructor(name: string) {
    
    
    super(name)
  }

  eat(): void {
    
    
    console.log(this.name, 'People类必须有eat方法')
  }

  work(): void {
    
    
    console.log(this.name, 'People类必须有work方法')
  }
}

const people = new People('某个人')
people.eat() // 某个人 People类必须有eat方法
people.work() // 某个人 People类必须有work方法
people.coding('在工作') // 某个人在工作

Guess you like

Origin blog.csdn.net/weixin_45559449/article/details/132340721