TS面向对象

48 阅读2分钟

一、类的基本使用

class Person {
  // 声明成员属性
  name: string = ""
  age: number = 0
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

const p1 = new Person("linxi", 18)

如果不进行编写声明成员会进行报错。类继承和js一样不再赘述

二、接口类型

1. 接口继承

interface Shape {
  color: string;
}
interface Square extends Shape {
  sideLength: number;
}
let square: Square = {
  color: 'blue',
  sideLength: 10,
};

一般用在封装库中自己不想再次定义可以直接使用继承第三方库

2. 类继承

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
  }
}

let dog = new Dog('Buddy');
dog.bark(); // 输出 "Woof! Woof!"
dog.move(10); // 输出 "Buddy moved 10 meters."

3.类实现接口

使用 implements 关键字来让一个类实现一个接口。类实现接口时,必须包含接口中定义的所有属性和方法,并且它们的类型和签名必须与接口中的定义相匹配

interface Shape {
  color: string;
  area(): number;
}

class Circle implements Shape {
  color: string;
  radius: number;

  constructor(color: string, radius: number) {
    this.color = color;
    this.radius = radius;
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

let myCircle = new Circle('red', 5);
console.log(`颜色: ${myCircle.color}`);
console.log(`面积: ${myCircle.area().toFixed(2)}`);

三、严格字面量赋值检测

先看示例

interface IAnim {
  name: string,
  age:number
}
const cat:IAnim={
  name:"猫",
  age:12,
  height:12,//这样会提示报错
}

但是如下写法:就显示正常不报错,ts没有做类型检查

interface IAnim {
  name: string,
  age: number
}

let obj = {
  name: "猫",
  age: 12,

  height: 12,
}
const cat: IAnim = obj

1·第一次创建的对象字面量,称之为新的

2.对于新鲜的字面量,会进行严格的类型检测、必须完全满足类型的要求(不能有多余的属性)

3.当新的对象字面量分配给一个变量或传递给一非空目标类型的参数时,对象字面量指定目标类型中不存在的属性是错误的

四、TS枚举类型

使用enum关键字

enum Dream {
  ONE,
  TWO,
  THREE
}

const d1: Dream = Dream.ONE

image.png

枚举默认值是0,1,2...,因此可以进行枚举赋值

enum Dream {
  ONE = "测试",
  TWO = "测试2",
  THREE = 1 << 1
}
const d1: Dream = Dream.THREE
console.log(d1)

更多的对象知识诸如抽象类、索引签名等理解可以查阅官网