— 类型注释(Type annotations)
类型注释是一个轻便的方式去记录函数或者变量希望得到的类型

1
2
3
4
5
function hello(person: string){
return 'hello' + person
}
let user = 'Jane User' // 传递字符串类型
console.log(hello(user)) // hello Jane User

如果传递的类型和函数参数期望的类型不一样,那么会得到如下的错误信息

1
2
3
4
5
function hello(person: string) {
return 'hello' + person
}
let user = [1,2,3] // 传递数组
console.log(hello(user)) // 报错: Argument of type 'number[]' is not assignable to parameter of type 'string'.

如果调用函数时,没有传递任何参数,那么也同样的会产生错误信息

1
2
3
4
function hello(person: string){
return 'hello' + person
}
console.log(hello()) // 不传递任何参数给函数,报错:An argument for 'person' was not provided.

  • typescript能够基于代码结构和类型注释提供静态分析

—- interface
在typescript中,两个类型是兼融的,只要它们内部的结构是兼融的。这个特性使得我们在实现接口的时候只要保证包含了接口要求的结构就可以了,而不必显示的使用implements语句

1
2
3
4
5
6
7
8
9
interface Person {
firstName: string,
lastName: string
}
function hello (person: Person) {
return 'hello ' + person.firstName + ' ' + person.lastName
}
let user = {firstName: 'Jane', lastName: 'user'}
console.log(hello(user)) // hello Jane user


—- Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Student {
fullName: string;
constructor(public firstName: string, public middleInitial: string, public lastName:string) {
this.fullName = firstname + middleInitial + lastName
}
}
interface Person {
firstName: string,
lastName: string
}
function hello(person: Person){
return 'hello ' + person.firstName + ' ' + person.lastName
}
let user = new Student("Jane", 'M' + 'User')
console.log(user) // {
// firstName: 'Jane',
// middleInitial: 'M',
// lastName: 'User',
// fullName: 'JaneMUser' }
console.log(hello(user)) // hello Jane User