布尔值 boolean true false
var flag:boolean=true
flag = false
数值类型 number
var num:number = 123
num = 2343
字符串类型 string
var str:string = 'dsd'
str = 'dsdkh'
数组类型 array
let arr:number[] = [21,212,1,877]
let arr1:string[] = ['我I','dsd','dsdaaa']
let arr2:Array<number> = [234,565,232]
let arr3:Array<string> = ['234','565','232']
元祖类型 tuple 属于数组的一种
let arr4:[string,number,boolean] = ['sd',23,false]
枚举类型 enum
enum Flag {
success=1,
error=-1,
primary
}
console.log(Flag.success);
任意类型 any
let tt2: any = 23232;
tt2 = 'dsds'
tt2 = null;
let list: any[] = [1, true, "free"];
null undefined
let u: undefined = undefined;
let n: null = null;
void
function noReturn():void {
console.log("This is my warning message")
}
let unusable1: void = undefined;
console.log(unusable1);
never 类型 永不存在的值的类型
- never 类型是任何类型的子类型。没有类型是 never 的子类型或可以赋值给never类型(除了never本身之外)
- 返回 never 的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为 never
function fail() {
return error("Something failed");
}
// 返回 never 的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
object
declare function create(o: object | null | undefined): void;
create({'da':23})
create({})
create(null)
create(undefined)
类型断言
- TypeScript 里使用 JSX 时,只有 as 语法断言是被允许的。
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length;
let strLength2: number = (someValue as string).length;
console.log(strLength1);
console.log(strLength2);