前言

随缘记录下TS的一些知识,随缘补充

TS的基础类型

  • Number
  • String
  • Boolean
  • Object
  • Array
  • Tuple
  • Any
  • Null
  • Undefined
  • Enum
  • Unknown
  • Void

然后介绍一下平时比较少用的几个

Tuple(元组)

1
2
3
4
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK

Unknown

表示一个变量的类型是未知的,每次使用前都要进行类型检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function foo() : string|number {
if (Math.random() < 0.5) {
return 0;
} else {
return ""
}
}

let data : unknown = foo();
let num = 10;
if (typeof data === "number") {
let sum = num + data;
console.log(sum);
}

any

表示一个变量的值可以是任何类型,并且去掉类型检查,如果不是有确切的把握或者实在不想要类型检查,不然最好不要乱用

1
2
3
4
5
function foo() : any {
return null;
}
// 不会报错
console.log(foo().data);

Void

通常用来表示一个函数没有返回值

1
2
3
function warnUser(): void {
console.log("This is my warning message");
}

如果一个变量被声明成了void类型,你只能给它赋值为undefined

要是没有开启–strictNullChecks,还可以赋值为null

1
2
3
let unusable: void = undefined;
// OK if `--strictNullChecks` is not given
unusable = null;

Null and Undefined

表示一个变量的类型是undefined或者null

默认情况下,undefinednull是所有类型的子类型,你可以把它们赋值给声明为number类型的变量

–strictNullChecks开启后,null和undefined只能赋值给unknown、any和它们各自的类型(除了undefined可以赋值给void)

Never

相比于void表示没有,never表示无法到达

Never一般用在下面三种情况

  • 永远抛出错误的函数
  • 死循环的函数
  • 无法到达的分支
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Function returning never must not have a reachable end point
function error(message: string): never {
throw new Error(message);
}

// Inferred return type is never
function fail() {
return error("Something failed");
}

// Function returning never must not have a reachable end point
function infiniteLoop(): never {
while (true) {}
}

function foo(data : number|string) {
if (typeof data === "number") {
// ...
} else if (typeof data === "string") {
// ...
} else {
let rua = data;
// Property 'name' does not exist on type 'never'.
console.log(rua.name)
}
}

type和interface的区别

type是类型别名,interface是接口

  • interface可以在声明函数类型时同时声明一些属性
1
2
3
4
5
6
7
8
9
10
11
12
13
// 无法再声明其他的属性
type Type = (num : number) => number;

interface IType {
(num : number) : void;
_cache : Array<number>
}

const foo : IType = function () {

}

foo._cache = []

我也很少用,也就在刷leetcode时写斐波那契数列时用过

  • type可以声明一些interface无法表示的类型,比如union和tuple
1
2
3
4
5
// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];
  • interface对相同的声明会进行合并
1
2
3
4
5
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

这玩意可以声明一些全局方法,比如给Array添加一个remove方法用于移除指定下标

1
2
3
interface Array<T> {
remove(index : number) : Array<T>
}

另外我还找到了这张图,可以看看

image-20210204213714283

接口和抽象类的区别

  1. 类可以实现(implement)多个接口,但只能扩展(extends)自一个抽象类。
  2. 抽象类中可以包含具体实现,接口不能。
  3. 抽象类在运行时是可见的,可以通过 instanceof 判断。接口则只在编译时起作用。

怎么在解构时进行类型声明

1
2
3
4
5
6
7
type Type = {
name : string,
age : number
}
function foo({name, age} : Type) {
console.log(name , age);
}

FAQ & Refer

Typescript文档

深入理解Typescript