千家信息网

TypeScript中的class和interface怎么用

发表于:2024-10-02 作者:千家信息网编辑
千家信息网最后更新 2024年10月02日,这篇文章主要介绍了TypeScript中的class和interface怎么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇TypeScript中的class和inter
千家信息网最后更新 2024年10月02日TypeScript中的class和interface怎么用

这篇文章主要介绍了TypeScript中的class和interface怎么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇TypeScript中的class和interface怎么用文章都会有所收获,下面我们一起来看看吧。

class

首页我们要清楚的一点是 TypeScript 中类和 JavaScript 中ES6语法类的区别,千万不要混淆。ts 中相比于 js 添加了声明属性的类型和参数的类型以及返回结果类型。这个地方一看就会一写就不对,如果不声明 ts 会报错。

class Person{    name:string;    constructor(name:string){        this.name = name;    }    getName():void{        console.log(this.name);    }}
class Person{    constructor(name){        this.name = name;    }    getName(){        console.log(this.name);    }}

ES5编辑后的结果

var Person = /** @class */ (function () {    function Person(name) {        this.name = name;    }    Person.prototype.getName = function () {        console.log(this.name);    };    return Person;}());
类的get和set

ts 在编译 get 和 set 的时候默认是 es3 编译,vscode 编辑器会报错error TS1056: Accessors are only available when targeting ECMAScript 5 and higher需要编译到版本 ES5 或以上,解决办法:$ tsc xxx.ts -t es5

class User{    myname:string;    constructor(myname:string){        this.myname = myname    }    get name(){        return this.myname    }    set name(newName:string){        this.myname = newName    }}

ES5编译后的结果

var User = /** @class */ (function () {    function User(myname) {        this.myname = myname;    }    Object.defineProperty(User.prototype, "name", {        get: function () {            return this.myname;        },        set: function (newName) {            this.myname = newName;        },        enumerable: false,        configurable: true    });    return User;}());

这里有几个思考问题,答案见文末:

var u = new User("a");console.log(u);console.log(u.myname);u.myname = 'b';console.log(u.myname);console.log(u.hasOwnProperty("name"));console.log(Object.getPrototypeOf(u));console.log(Object.getPrototypeOf(u).hasOwnProperty("name"));
抽象类

abstract关键字表示抽象类,抽象类是不能被实例化即new,只能被继承,抽象类一般是用来封装一些公共的,提供给子类使用的方法和属性的

abstract class Animal{    public readonly name:string;    protected age:number = 38;    private money:number = 10;    constructor(name:string){        this.name = name    }}class Dog extends Animal{    static className = 'Dog'    static getClassName(){        console.log(this.className)    }    getName(){        console.log(this.name)    }    getAge(){        console.log(this.age)    }}let a = new Animal("ss");

这里打印看一下继承的结果:

console.log(a); //Dog { age: 38, money: 10, name: 'ss' }

这里顺便说一下访问修饰符 public protected private

  • public 里里外外都能访问,包括自己、自己的子类、其他类都能

  • protected 自己和子类能访问但是其他地方不能访问

  • private 私有的(只有自己能访问,子类的其他都不能访问)

interface

接口表示对象的属性
interface Rectangle {    width: number;    height: number}let r: Rectangle = {    width: 100, height: 10}interface Speakable {    speak(): void;    name?: string}let speaker: Speakable = {    //name:"bdt",    speak() { }}
接口用来描述抽象的行为
interface AnimalLink {    eat(): void;    move(): void}
接口可以实现继承
interface PersonLike extends AnimalLink {    speak(): void}class Person2 implements PersonLike {    speak() { };    eat() { };    move() { }}
通过接口约束变量类型
interface Person3 {    readonly id: number;    name: string;    [PropName: string]: any}let p1: Person3 = {    id: 1,    name: "sss"}
通过接口约束(规范)函数
interface DiscountInterface{    (price:number):number}let discount:DiscountInterface = function (price: number): number {    return price * .8}
通过索引约束数组和对象
interface UserInterface{    [index:number]:string}let arr:UserInterface = ['aa','bb']interface UserInterface2{    [index:string]:string}let obj:UserInterface2  = {name:"sss"}
通过接口约束构造函数
class Animal3{    constructor(public name:string){}}interface WithClassName{    new (name:string):Animal3}function createClass(clazz:WithClassName,name:string){    return new clazz(name)}let a3 = createClass(Animal3,"别抖腿");console.log(a3)

class和interface的区别

  • class 类声明并实现方法

  • interface 接口声明,但是不能实现方法

abstract class Animal{    name:string="111";    abstract speak():void;  //抽象类和方法不包含具体实现  必须在子类中实现}//接口里的方法都是抽象的interface Flying{    fly():void}interface Eating{    eat():void}class Dog extends Animal{    speak(){        console.log("汪汪汪")   //重写:子类重写继承自父类中的方法    }}class Cat extends Animal implements Flying,Eating{    speak(){   //继承抽象类的方法必须实现        console.log("喵喵喵")    }    fly(){        console.log("我是一只飞货")    }    eat(){        console.log("我是一只吃货")    }}

文中答案

User { myname: 'a' }ab falseUser { name: [Getter/Setter] }true

关于"TypeScript中的class和interface怎么用"这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对"TypeScript中的class和interface怎么用"知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。

0