前言:ts 对数据类型进行约束及检测。比如:数据约束了是 number 值,给它赋值 string 或 boolean 值时,ts 会报错。
1. ts 数据类型
布尔值、数字、字符串、数组、元组、枚举、Any、Void、Null、Undefined、Nerver、Object、类型断言
2. 例子
// 布尔值 let tsBoolean: boolean = false; // 数字 let tsNumber: number = 123; // 字符串 let tsString: string = "abc"; // 数组 let tsListNum: number[] = [1, 2, 3, 4]; let tsListStr: string[] = ["A", "B", "C", "D"]; let tsListMix: any[] = ["A", 1, "B", 2, { a: 12 }]; let tsLintStr2: Array<string> = ["A", "B", "C", "D"]; // 元组 let tsTuple: [string, number] = ["AA", 222]; // 枚举 enum Color { Red, Green, Pink, } let tsEnum: Color = Color.Green; // Null let tsNull: null = null; // Undefined let tsUndefined: undefined = undefined; // Object let tsObject: object = { a: "aaaa" }; // Void function tsVoidFun(a: string, b: string): void { console.log(a + b); } // Nerver function error(message: string): nerver { throw new Error(message); } // 类型断言 let strLength: number = (someValue as string).length;
下一章:下一站:前端 TS 快速入门之二:接口