TypeScipt的class、interface、type区别

 

class

类的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;
}());
复制代码

 

抽象类

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)
复制代码

 

 

type

描述一个对象或者函数

type User = {
    name: string;
    age: number
}
type SetUser
= (name: string, age: number): void;

拓展(extends)

type Name = {
    name: string;
}

type User = Name & { age: number }

interface extends type

type Name = {
    name: string;
}

interface User extends Name {
    age: number;
}

type extends interface

interface Name {
    name: string;
}

type User = Name & {
    age: number;
}

 

type和interface区别

type声明的方式可以定义组合类型、交叉类型和原始类型

复制代码
// 基本类型别名
type Name = string;

// 联合类型
interface Dog {
    wong()
}
interface Cat {
    miao();
}

type Pet = Dog | Cat;

// 具体定义数组每个位置的类型
type PetList = [Dog, Pet];
复制代码

type语句中还可以使用typeof获取实例的类型进行赋值

// 当你想要获取一个变量的类型时,使用typeof
let div = document.createElement('div');
type B = typeof div;

type其他骚操作

type StringOrNumber = string | number;
type Text = string | { text: string };
type NameLookup = Dictionary<string, Person>;
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

interface能够声明合并

 interface User {
    name: string;
    age: number;
}

interface User {
    sex: string;
}

 

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("我是一只吃货")
    }
}
复制代码

 

 

参考网址

https://zhuanlan.zhihu.com/p/431612051

 

posted @   泠风lj  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示