TypeScript学习笔记

TypeScript学习笔记

二月 10, 2021

TypeScript学习笔记

参考资料

https://www.tslang.cn/docs/handbook/basic-types.html

https://blog.csdn.net/lihefei_coder/article/details/103712497

正篇

安装

1
2
npm install -g typescript
npm install ts-node -g

类型、参数注解

typescript相较于js添加了类型、参数注解
类似于从之前javascriptphppython这样的动态语言
转换为像javaC++c这样的静态语言书写方式

这里举几个简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
let author: string = "Yoshino"
let date: number = 1224
let isElves: boolean = true
let listString: string[] = ['1', '2', '3'];
let listnumber: Array<number> = [1, 2, 3];
let x: [string, number] = ["a", 1]
// 这样的声明,也是不可以改变的
function love(params: string): void {
console.log(`yoshino love ${params}`)
}
love('Akeno')
let hello: any

注意:这里的类型声明与java这里静态语言一样,除非进行类型转换,否则声明是什么就是什么
如果不声明的话,就是any

当然typescript只是js的超集而已

1
2
3
4
5
6
7
let myObj: Object = {}
setTimeout(() => {
myObj.fun()
}, 3000)
// 报错
console.log(0.999999999999999999999999999999999999999999999)
// 输出1

这里是其他相关的探究,可以忽略

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
enum Color {
Red = 1,
'Green',
Blue,
Cyan,
Magenta,
Yellow = 3,
blacK ,
}
console.log(Color.Magenta, Color['blacK'])
// for(let i in Color){
// console.log(i)
// }
for(let i = 0; i < 10; i++){
console.log(i, Color[i], typeof(Color[i]))
}

// let color: Color = Color[1]
// console.log(color)

// 输出
// 5 4
// 0 undefined undefined
// 1 Red string
// 2 Green string
// 3 Yellow string
// 4 blacK string
// 5 Magenta string
// 6 undefined undefined
// 7 undefined undefined
// 8 undefined undefined
// 9 undefined undefined

let a: any[]
// a = {}
a = [10,"Hello","World","typeScript", {}]

let b: Object
b = [10,"Hello","World","typeScript", {}]


function create(o: object | null): void{
};

create({ prop: 0 }); // OK
create(null); // OK

// create(42); // Error
// create("string"); // Error
// create(false); // Error
// create(undefined); // Error

// 使用declare function声明函数。
declare function create1(o: object | null): void;

类和接口

这里的内容我觉得和java差不多
所以只简单列举下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 必选
interface LabelledValue {
label: string;
}
// 可选
interface SquareConfig {
color?: string;
width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}

let mySquare = createSquare({color: "black"});

只读

1
2
3
4
interface Point {
readonly x: number;
readonly y: number;
}