any 与 unknow
unknow不能保证类型,但可以保证类型安全
any 保证js的灵活性
类型断言 Type Assertions
object
ts 中 在对象定义时就已经隐式定义了对象类型
对象定义为 any 类型,可以访问对象中不存在的属性
Interface
Class
Interface 与 Class
概念区别
- interface是仅存在于TS上下文中的一种虚拟结构,TS编译器依赖接口用于类型检查,最终编译为JS后,接口将会被移除。
- 与interface不同,class作为TS的一种变量类型存在于上下文之中,class中可以提供变量、方法等的具体实现方式等,它的作用不仅仅是约束数据结构。
使用区别
当需要使用class时,我通常会考虑三个方面
- 是否需要创建多个实例
- 是否需要使用继承
- 是否需要特定的单例对象
对于从服务器端获取或者业务场景中模拟的数据,提倡使用 interface 去定义,这些数据通常是不会经常变化和调整的,这些数据可能仅仅只表示某些状态,或者是UI上的文本。
class MyClass {
a: number;
b: string;
origin: MyInterface;
constructor(options: MyInterface) {
this.a = options.a;
this.b = options.b;
this.origin = options; // 保存原始的options数据
}
foo(): void {
console.log(this.a);
console.log(this.b);
}
}
const a = new MyClass(options);
const b = new MyClass(a.origin);
在实际场景中,我们可以给class的参数指定好interface类型用来初始化class中的属性,以上代码在class的origin属性中保存了options的数据,可以用来之后初始化全新的class实例,这解决了class实例在变化后很难clone出全新实例的问题,上面实例中 b
变量 由 a
变量 的 orgin 字段初始化。
参考链接:
TypeScript 中的类和接口
ts在线编译
类实现接口
举例来说,门是一个类,防盗门是门的子类。如果防盗门有一个报警器的功能,我们可以简单的给防盗门添加一个报警方法。这时候如果有另一个类,车,也有报警器的功能,就可以考虑把报警器提取出来,作为一个接口,防盗门和车都去实现它:
interface Alarm {
alert(): void;
}
class Door {
}
class SecurityDoor extends Door implements Alarm {
alert() {
console.log('SecurityDoor alert');
}
}
class Car implements Alarm {
alert() {
console.log('Car alert');
}
}
一个类可以实现多个接口
interface Alarm {
alert(): void;
}
interface Light {
lightOn(): void;
lightOff(): void;
}
class Car implements Alarm, Light {
alert() {
console.log('Car alert');
}
lightOn() {
console.log('Car light on');
}
lightOff() {
console.log('Car light off');
}
}
接口继承接口
interface Alarm {
alert(): void;
}
interface LightableAlarm extends Alarm {
lightOn(): void;
lightOff(): void;
}
接口继承类
常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
为什么 TypeScript 会支持接口继承类呢?
实际上,当我们在声明 class Point
时,除了会创建一个名为 Point
的类之外,同时也创建了一个名为 Point
的类型(实例的类型)。
所以我们既可以将 Point
当做一个类来用(使用 new Point
创建它的实例):
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);
也可以将 Point
当做一个类型来用(使用 : Point
表示参数的类型):
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function printPoint(p: Point) {
console.log(p.x, p.y);
}
printPoint(new Point(1, 2));
参考资料:TypeScript的接口(interface)和类(class)
类与继承
- 传统方法中,JavaScript 通过构造函数实现类的概念,通过原型链实现继承。
- ES6 中使用 class 实现
- 抽象类是供其他类继承的基类,抽象类不允许被实例化。
- 抽象类中的抽象方法必须在子类中被实现