1.Number, String, Boolean, Undefined, Null类型
let num1: number = 132
let num2: number = 0b1010 //支持ESM进制表示
let str1: string = 'hello world'
let str2: string = `ts ${str1}` //支持字符串模板
let boo: boolean = true
/*undefined, null是其他数据类型的基础型*/
let defined1: undefined = undefined
let defined2: null = null
let defined3: number = undefined || null
let defined4: string = undefined || null
2.数组, 元组
let arr1: number[] = [1, 2]
let arr2: Array<number> = [1, 2]
let arr3: [string, number] = ['a', 1]
3.枚举
enum Color {
red,
blue = 1,
green
}
let enu1: Color = Color.red
let enu2: string = Color[1]
4.任意值
let something: any = 'asdasd'
something.dosome()
something.nothing() //可以赋任意值,也可以调任何方法,编译跳过类型检查,适用于动态值
5.Object
let obj: Object = 4
// obj.getSomething(); 可以赋任意值,不可以调不存在的方法
6.空值
function test(): void {
alert('2132')
} //当一个函数没有返回值时,你通常会见到其返回值类型是void
let unusable1: void = undefined
let unusable2: void = null // 空值只能赋予null, undefined
7.Never
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message)
}
// 推断的返回值类型为never
function fail() {
return error('Something failed')
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {}
}
8.类型断言
let someValue: string = "hello world!";
let strLength: number = (<string>something).length;
let strlen: number = (someValue as string).length;
网友评论