Vue3
Node.js
TypeScript
路由
接口请求
状态管理
实战项目
求职与未来发展
类型
类型检查
TypeScript
最主要的功能就是它的类型检查了,假如我们尝试给一个变量赋值类型不匹配的值,则会报错。
// Type 'string' is not assignable to type 'number'.
const hello: number = "你好~"
console.log(hello)
基础类型
数字、字符串、布尔
这几个类型比较简单,直接在初始化时跟上类型名就行。
const a: number = 123 // 数字类型
const b: string = "hello" // 字符串类型
const c: boolean = true // 布尔类型
数组
我们可以像以下一样定义数组类型,定义数组类型后,数组内所有的元素类型都必须与声明的类型保持一致。
const nums: number[] = [1, 2, 3] // 数字数组
const strs: string[] = ["x", "y", "z"] // 字符串数组
nums[0] = 7 // ok
// nums[0] = "test" // Type 'string' is not assignable to type 'number'.
数组的定义是很灵活的,也可以使用泛型定义。
let arr: Array<number> = [1, 2, 3] // 泛型定义
有时我们想要让数组支持多个类型时可以如以下方式定义。
let arr: (string | number)[]
arr = [1, 2, "3"] // ok
arr = [1, 2, false] // Type 'boolean' is not assignable to type 'string | number'.
元组
元组不属于 JavaScript 中的类型,它表示的是一个已知元素数量和类型的数组,各元素的类型不必相同。
let mingren: [string, number]
mingren = ["鸣人", 18] // ok
mingren = [18, "鸣人"] // error
枚举
枚举同样是 JavaScript 中没有的类型,使用枚举可以为一组值赋予友好的名字。
enum Color {
Red,
Green,
Blue,
}
const color: Color = Color.Green
console.log(color) // 2
any
any
表示其可以是任意类型, any
类型的变量可以被任意类型数据赋值,也可以赋值到任意类型的变量。
let n: any = 123
n = "hello" // ok,可以被赋值任意类型
let x: boolean = n // ok,也可以赋值到任意类型
$$tip
不推荐使用 any
类型,因为失去了类型的限制,这会让使用 TypeScript
毫无意义。
$$
void
void
则没有表示任何类型,比如一个函数没有返回值时,我们通常将其设置为 void
。
function sayHello(): void {
console.log("你好")
}
如果将一个变量声明为 void
,那么只能接收 undefined
的值。
let unusable: void = undefined
// unusable = 123 // Type 'number' is not assignable to type 'void'.
// unusable = null // Type 'null' is not assignable to type 'void'.
$$tip
一般不会将一个变量声明为 void
类型,没有意义。
$$
null 和 undefined
null
和 undefined
有各自的类型 null
和 undefined
。
let x: null = null
let y: undefined = undefined
$$tip
同理,一般不会将一个变量声明为 null
和 undefined
类型,没有意义。
$$
never
never
类型表示的是那些永不存在的值的类型。 例如, never
类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型。
function error(): never {
throw new Error("错误")
}
类型推导
如果一个变量在声明同时赋初始值时未声明类型,则自动将其类型定义为其初始值的数据类型。
let hello = 123456
// Type 'string' is not assignable to type 'number'.
hello = "你好~"
console.log(hello)
类型断言
有的时候我们知道某个变量应该是某个类型时,我们可以指定其类型。
let someValue: any = "this is a string"
let len: number = (<string>someValue).length
// 或者
let len2: number = (someValue as string).length