一、类的定义
class Person { // 实例属性 通过对象访问 name: string; // 类属性 通过类访问(静态属性) static age: number = 18; // 只读属性 readonly address = "中国"; constructor(name: string) { this.name = name; } // 定义方法 sayHello() { console.log("Hello") } static sayHi() { console.log("hi") } } const p1 = new Person("孙悟空") console.log(p1); p1.name = "猪八戒" console.log(p1); console.log(Person.age); console.log(p1.address); p1.sayHello(); Person.sayHi();
二、类的继承
class Animal { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } sayHello() { console.log("Animal sayHello") } } class Dog extends Animal { color: string; constructor(name: string, age: number, color: string) { // 调用父类的构造函数 super(name, age); this.color = color; } run() { console.log('${this.name}在跑') } sayHello() { // 调用父类的方法 super.sayHello(); console.log("汪汪") } } class Cat extends Animal { sayHello() { console.log("喵喵喵") } } const cat = new Cat("mimi", 3); console.log(cat); cat.sayHello(); const dog = new Dog("旺财", 5, "黑色"); console.log(dog); dog.sayHello(); dog.run()
三、抽象类
// 定义抽象类 不能创建实例,只能继承 abstract class Animal { name: string; constructor(name: string) { this.name = name; } // 定义抽象方法,没有方法体,子类必须对抽象方法进行重写,抽象方法只能定义到抽象类中 abstract sayHello(): void ; } class Dog extends Animal { sayHello(): void { console.log("汪汪") } } const dog = new Dog("旺财"); console.log(dog); dog.sayHello();
四、接口
// 描述一个对象的类别 type myType = { name: string, age: number } /* 接口用来定义一个类结构,用来定义一个类中应该包含那些属性和方法 接口也可以当成类型声明使用 */ interface myInterface { name: string; age: number; } interface myInterface { gender: string; } const obj: myInterface = { name: "接口", age: 111, gender: "男" } /* 接口可以限制类的结构 接口指定以对象的结构,接口中的属性不能有值 接口中的方法都是抽象方法 */ interface myInter { name: string; sayHello(): void; } /* 定义类,可以实现一个接口 */ class MyClass implements myInter { name: string; constructor(name: string) { this.name = name } sayHello(): void { } }
五、类属性的封装
// 定义一个人的类 class Person { /* public 修饰的属性可以在任意位置访问 protected 受保护的属性,可以在子类中访问 private 修饰的属性只能在类的内部修改 */ public _name: string; protected _address = "china"; private age: number; constructor(name: string, age: number) { this._name = name; this.age = age; } get name() { return this._name; } set name(value) { this._name = value; } } const per = new Person("孙悟空", 18); console.log(per); class Cat { // name:string; // age:number; // constructor(name: string, age: number) { // this.name=name; // this.age=age; // } // 属性定义、构造函数简写 constructor(public name: string, public age: number) { } } const cat = new Cat("mimi", 3); console.log(cat)
六、泛型
function fn<T>(a: T): T { return a; } console.log(fn("a")) // 泛型可以指定多个 function fn2<T, K>(a: T, b: K): T { console.log(b) return a; } fn2<string, number>("abc", 123); interface Inter { length: number; } function fn3<T extends Inter>(obj: T): number { return obj.length; } fn3("123"); fn3({length: 5}) class MyClass<T> { name: T; constructor(name: T) { this.name = name; } } const mc = new MyClass<string>("孙悟空") const mc2 = new MyClass("孙悟空")