interface

  • 在面向对象编程中,用作行为的抽象
  • 描述对象的形状 ```typescript interface Person { name: string; age?: number; //?为可选属性 [propName: string]: any //用方括号定义[任意名称],就可以添加无限多的任意属性,也可将类型设为联合类型:string | number }

let mmo: Person = { //创建一个interface对象,且只能按对象格式新建 name: ‘mmo’, age: 18, gender: ‘male’ //如果没有定义任意属性会报错, 但上方已定义了任意属性,所以最终不会报错 }

  1. 另一种声明赋方式
  2. ```typescript
  3. //正确
  4. //本选项为一个对象类型,且结构类型与赋值对象结构类型相符
  5. const animal: {weight: number ; isMammal: boolean} = {
  6. weight: 10,
  7. isMammal: true
  8. }
  9. //任何不确定类型的变量都可以声明为 any
  10. const animal: any = {
  11. weight: 10,
  12. isMammal: true
  13. }
  14. //错误
  15. //这是基本数据类型,不是interface对象类型
  16. const animal: number | boolean = {
  17. weight: 10,
  18. isMammal: true
  19. }
  20. //错误写法
  21. const animal: {number | boolean} = {
  22. weight: 10,
  23. isMammal: true
  24. }

类型推论 - 对象

//类型推论 - 对象, 自动推论
let a = {
    name: 'mmo',
    age: 18,
    gender: 'male'  
}

复杂的对象

interface Person22_3 {
    name: string,
    gender: string,
    friend: {
        name: string,
        gender: string,
    }
}

let a22_3: Person22_3 = {
    name: 'mmo',
    gender: 'male' ,
    friend: {
        name: 'aaa',
        gender: 'male'
    }
}

类型推论 - 对象(严格模式)

//变量 animal 被赋值为对象,因此变量 animal 会被推论为具体的对象类型。
//与上方不同,上方为可声明的类型,但是由于此处没有声明,所以会被推论为具体的
//: {weight: number ; isMammal: boolean}
const animal_22_2 = {
    weight: 10,
    isMammal: true
}

类型别名

//interface和类型别名的区别,面向对象主要使用interface

interface Person22_4 {    //不能使用联合类型
  name: string,
  gender: string,
  friend: {
    name: string,
    age: number,
  }
}

type =  Person22_4 {    //可以使用联合类型
  name: string,
  gender: string,
  friend: {
    name: string,
    age: number,
  }
}


let a22_4: Person22_4 = {
  name: 'mmo',
  gender: 'male',
  friend: {
    name: 'aaa',
    age: 18,
    gender: 'male'
  }
}

image.png

答案

D

解析

类型别名使得我们可以对一个比较复杂的类型重命名,从而提高代码阅读性。

  • A - name 被赋值 panda,所以声明为 string 是正确的。
  • B - weight 被赋值 10,所以声明为 number 是正确的。
  • C - 变量 animal 被赋值为一个对象,本选项将 animal 声明为对象类型,且和赋值对象的结构类型相符。故正确。
  • D - 变量 animal 被赋值为一个对象,但本选项声明的联合类型中均为基本数据类型。故错误。