App下載

TypeScript 中的class和interface

猿友 2020-09-23 14:00:39 瀏覽數(shù) (3856)
反饋

文章來源于公眾號(hào):小丑的小屋

前言

剛剛的vue3.0一發(fā)布,各大網(wǎng)址和社區(qū)以及公眾號(hào)已經(jīng)被 Vue3.0 的One Piece版本所霸屏,出現(xiàn)不同的標(biāo)題有著同樣內(nèi)容的現(xiàn)象,借此熱度我們不如好好回顧一下ts基礎(chǔ)知識(shí),備戰(zhàn)vue3.0的正式使用。

TypeScript 這個(gè)東西說實(shí)在的,真的是容易忘記,一段時(shí)間不用就感覺特別陌生,但是回過頭來看看,又有一種熟悉的感覺,有句話是這么說的:ts越用越香,它確實(shí)能夠規(guī)范我們的書寫的格式,語法校驗(yàn)和類型校驗(yàn)等。之前寫過react+ts的一個(gè)demo,但是時(shí)間久了就忘記了,現(xiàn)在也是趁著熱度再回顧一下ts的內(nèi)容,以及一些高階語法,現(xiàn)在我們回顧一下ts中常見的類和接口。

class

首頁我們要清楚的一點(diǎn)是 TypeScript 中類和 JavaScript 中ES6語法類的區(qū)別,千萬不要混淆。ts 中相比于 js 添加了聲明屬性的類型和參數(shù)的類型以及返回結(jié)果類型。這個(gè)地方一看就會(huì)一寫就不對(duì),如果不聲明 ts 會(huì)報(bào)錯(cuò)。

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編輯后的結(jié)果

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 的時(shí)候默認(rèn)是 es3 編譯,vscode 編輯器會(huì)報(bào)錯(cuò)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編譯后的結(jié)果

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;
}());

這里有幾個(gè)思考問題,答案見文末:

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關(guān)鍵字表示抽象類,抽象類是不能被實(shí)例化即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");

這里打印看一下繼承的結(jié)果:

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

這里順便說一下訪問修飾符 public protected private

  • public 里里外外都能訪問,包括自己、自己的子類、其他類都能
  • protected 自己和子類能訪問但是其他地方不能訪問
  • private 私有的(只有自己能訪問,子類的其他都不能訪問)

interface

interface

接口表示對(duì)象的屬性

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
}

接口可以實(shí)現(xiàn)繼承

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"
}

通過接口約束(規(guī)范)函數(shù)

interface DiscountInterface{
    (price:number):number
}
let discount:DiscountInterface = function (price: number): number {
    return price * .8
}

通過索引約束數(shù)組和對(duì)象

interface UserInterface{
    [index:number]:string
}


let arr:UserInterface = ['aa','bb']


interface UserInterface2{
    [index:string]:string
}
let obj:UserInterface2  = {name:"sss"}

通過接口約束構(gòu)造函數(shù)

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的區(qū)別

  • class 類聲明并實(shí)現(xiàn)方法
  • interface 接口聲明,但是不能實(shí)現(xiàn)方法

abstract class Animal{
    name:string="111";
    abstract speak():void;  //抽象類和方法不包含具體實(shí)現(xiàn)  必須在子類中實(shí)現(xiàn)
}
//接口里的方法都是抽象的
interface Flying{
    fly():void
}
interface Eating{
    eat():void
}
class Dog extends Animal{
    speak(){
        console.log("汪汪汪")   //重寫:子類重寫繼承自父類中的方法
    }
}
class Cat extends Animal implements Flying,Eating{
    speak(){   //繼承抽象類的方法必須實(shí)現(xiàn)
        console.log("喵喵喵")
    }
    fly(){
        console.log("我是一只飛貨")
    }
    eat(){
        console.log("我是一只吃貨")
    }
}

寫在最后

文中答案

User { myname: 'a' }
a
b 
false
User { name: [Getter/Setter] }
true

以上就是W3Cschool編程獅關(guān)于TypeScript 中的class和interface的相關(guān)介紹了,希望對(duì)大家有所幫助。

0 人點(diǎn)贊