- 任意类型,关键字
any
- 要注意的是,过度使用
any 类型和双重类型断言可能会降低ts的类型安全性,从而使我们失去使用ts的主要优点
- 数字类型,关键字
number - 字符串类型,关键字
string - 布尔类型,关键字
boolean - 数组类型,没有关键字
- 在元素类型后面加上
[],比如 number[]、string[] - 使用数组泛型
Array<number>、Array<string>
- 元组类型,没有关键字
- 元组类型用来表示已知元素数量和类型的数组,各元素的类型不必相同,对应位置的类型需要相同
const x:[number, string] = [1, 'a'] 约束 x 是一个元组类型,只能存在两个成员,且第一个成员必须是数字类型,第二个成员必须是字符串类型
- 枚举类型,关键字
enum
- 枚举类型用于定义数值集合
- void 类型,关键字
void
- void 用于标识方法返回值的类型,表示该方法没有返回值
- null 类型,关键字
null
null 表示对象值缺失
- undefined 类型,关键字
undefined
- undefined 用于初始化变量为一个未定义的值
- never 类型,关键字
never
- never 是其它类型(包括 null 和 undefined)的子类型,代表从不会出现的值
- Any 任意值是 ts 针对编程时类型不明确的变量使用的一种数据类型
- 任意值类型可以让变量跳过编译阶段的类型检查
let x1: any = 1; // 数字类型x1 = 'I am who I am'; // 字符串类型x1 = false; // 布尔类型let x2: any = 4;x2.ifItExists(); // 正确,ifItExists方法在运行时可能存在,但这里并不会检查x2.toFixed(); // 正确// 定义存储各种类型数据的数组let arrayList: any[] = [1, false, 'fine'];arrayList[1] = 100;
- Null 和 Undefined 是其他任何类型(包括 void)的子类型,可以赋值给其它类型,如数字类型,此时,赋值后的类型会变成 null 或 undefined
- 在 ts 中启用严格的空校验
--strictNullChecks特性,就可以使得 null 和 undefined 只能被赋值给 void 或本身对应的类型
// 启用 --strictNullCheckslet x1: number;x1 = 1; // 编译正确x1 = undefined; // 编译错误x1 = null; // 编译错误// 启用 --strictNullCheckslet x2: number | null | undefined;x2 = 1; // 编译正确x2 = undefined; // 编译正确x2 = null; // 编译正确
- never 是其它类型(包括 null 和 undefined)的子类型,代表从不会出现的值
- 声明为 never 类型的变量只能被 never 类型所赋值
let x: never;let y: number;// 编译错误,数字类型不能转为 never 类型x = 123;// 运行正确,never 类型可以赋值给 never类型x = (()=>{ throw new Error('exception')})();// 运行正确,never 类型可以赋值给 数字类型y = (()=>{ throw new Error('exception')})();// 返回值为 never 的函数可以是抛出异常的情况function error(message: string): never { throw new Error(message);}// 返回值为 never 的函数可以是无法被执行到的终止点的情况function loop(): never { while (true) {}}
- ts 中变量的命名规则和 js 中一致
- 在 ts 中声明变量的同时,可以指定变量的数据类型
let <变量名>: <类型>
var uname: string = "Runoob";var score1: number = 50;var score2: number = 42.50var sum = score1 + score2console.log("名字: " + uname)console.log("第一个科目成绩: " + score1)console.log("第二个科目成绩: " + score2)console.log("总成绩: " + sum)// 名字: Runoob// 第一个科目成绩: 50// 第二个科目成绩: 42.5// 总成绩: 92.5