TypeScript 学习总结 —— 抽象类 abstract class 和接口 interface

  • 抽象类abstract class
// 定义一个抽象类,不能直接实例化,需要其他类继承并实现全部抽象方法
abstract class Animal {
    readonly name;	// 只读属性
    constructor (name: string) {
        this.name = name
    }

	// 抽象方法
    abstract sayName():void
}

// 继承抽象类,并实习抽象方法
class Dog extends Animal {
    sayName () {
        console.log(`汪汪 ${this.name}`)
    }
}

let d = new Dog('bai')

d.sayName()
  • 接口 interface
// 定义接口,接口只能描述类的结构,不能有实际的实现
interface Animal {
    name: string
    sayName():void
}
// 实现接口
class Dog implements Animal {
    name
    constructor (name:string) {
        this.name = name
    }
    sayName () {
        console.log(`汪汪 ${this.name}`)
    }
}

let d = new Dog('bai')

d.sayName()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
TypeScript 中,类和接口是两个重要的概念,用于面向对象编程和定义对象的结构。下面是关于 TypeScript 中类和接口的一些重要信息: 1. 类(Classes): - 类是对象的蓝图,用于定义对象的属性和方法。 - 使用 `class` 关键字来定义一个类,并使用构造函数来初始化类的实例。 - 可以使用 `public`、`private` 和 `protected` 访问修饰符来控制成员的可见性。 - 可以使用 `extends` 关键字来实现类之间的继承。 - 类可以包含属性、方法和构造函数。 以下是一个使用 TypeScript 定义和使用类的示例: ```typescript class Person { private name: string; constructor(name: string) { this.name = name; } public greet() { console.log(`Hello, ${this.name}!`); } } const person = new Person("John"); person.greet(); // 输出:Hello, John! ``` 2. 接口Interfaces): - 接口用于定义对象的结构或类的契约,并且在 TypeScript 中被广泛用于类型检查和类型推断。 - 使用 `interface` 关键字来定义一个接口,并在接口中定义属性和方法的签名。 - 接口可以被类实现(使用 `implements` 关键字)或对象使用(使用 `:` 进行类型注解)。 - 接口可以继承其他接口,以便组合多个接口的结构。 - 接口的属性可以是可选的,使用 `?` 来标记。 以下是一个使用 TypeScript 定义和使用接口的示例: ```typescript 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() { return Math.PI * this.radius * this.radius; } } const circle: Shape = new Circle("red", 5); console.log(circle.area()); // 输出:78.53981633974483 ``` 通过使用类和接口,你可以更好地组织和定义你的代码,并在编译时进行类型检查,以减少错误并提高代码的可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tanleiDD

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值