ts小记(一)
coolpail opened this issue · 0 comments
coolpail commented
any
any是最高也是最低
- any可以分配给任何类型
let a: any;
let b: number = a;
- 任何类型可以分配any
let a: any = 123
unknow
任何类型可以分配给unknow;当有类型防护时,能缩小类型范围
[..] unknown是任何类型安全的对应物。任何事物都可以分配给未知对象,但是未知事物不能分配给任何事物,只有它本身以及没有类型声明或基于控制流的缩小。同样,在未先声明或缩小为更具体的类型之前,不允许对未知数执行任何操作。
let a: unknown = 123;
declare const maybe: unknown;
if (maybe === true) {
// TypeScript knows that maybe is a boolean now
const aBoolean: boolean = maybe;
// So, it cannot be a string
const aString: string = maybe;
}
readonly number[]
- number[] 可以分配给 readonly number[];反过来就不行
解决多余属性检查
- 创建新变量作为函数入参,但需要有共同的某一个或多个属性
- 类型断言as
- 修改interface定义,增加
[propName: string]: unknown
用接口来描述函数
- 只需要函数的入参类型和返回值类型一致就行,不需要参数一样
interface fn {
(s: string, b: string): boolean
}
const f: fn = (a, b) => true
类实现接口
- 必须实现接口的方法和属性
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {} //这个构造函数没有强制绑定类型
}
类实现接口只实现实例属性,不是实现静态属性,所以下面例子报错
interface ClockConstructor {
new (hour: number, minute: number): void;
}
class Clock implements ClockConstructor {
//Class 'Clock' incorrectly implements interface 'ClockConstructor'.
//Type 'Clock' provides no match for the signature 'new (hour: number, minute: number): any'.
currentTime: Date;
constructor(h: number, m: number) {}
}
定义构造函数以及类的实现
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick(): void;
}
const Clock: ClockConstructor = class Clock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log("beep beep");
}
};
扩展接口(接口实现接口)
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
接口扩展类
class Control {
private state: any;
}
// 接口实现了继承了类,并拥有了私有属性state
interface SelectableControl extends Control {
select(): void;
}
// 因为Button继承了Control,也就继承了私有属性state,所以可以实现SelectableControl
class Button extends Control implements SelectableControl {
select() {}
}
class TextBox extends Control {
select() {}
}
//因为Button不拥有私有属性state,所以不可以实现SelectableControl
class ImageControl implements SelectableControl {
// Class 'ImageControl' incorrectly implements interface 'SelectableControl'.
// Types have separate declarations of a private property 'state'.
private state: any;
select() {}
}