基本类型
原始类型:number,string,boolean,symbol,null或undefined
写法参考:let isDone: boolean = false;
数组
方式一:let list: number[] = [1, 2, 3];
方式二:let list: Array<number> = [1, 2, 3];
元祖
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。
let x: [string, number];
x = ['hello', 10];
枚举
比如男女,红绿蓝这样的可以用枚举
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
void
当一个函数没有返回值时,你通常会见到其返回值类型是 void:
function warnUser(): void {
console.log("This is my warning message");
}
Never
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
Object
object表示非原始类型
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
类型断言
“尖括号”语法:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
as 语法:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;