类型
- 类型注解: 在变量、声明的后面立即加上冒号‘:’
类型注释应该使用小写 | // 字符串注释
const XXX: string = “string type”
// 布尔值注释
let trueor_false: boolean = false
// 函数参数类型注释
function params(_value: string) {
console.log(value) // 返回string类型
}
// 函数返回值类型注释
function returnValue(): string {
return ‘value is string’
} | | —- |类型说明 | 类型 | 标识 | 例子 | 备注 | | —- | —- | —- | —- | | 布尔型 | boolean | let isDone: boolean = false; | | | 数字 | number | let decLiteral: number = 6;
let hexLiteral: number = 0xf00d; | 需要使用整数时,需使用Number.parseInt()方法,其他类似 | | 字符串 | string | let name: string = ‘bob’;
name = “smith”; | 可以使用(“)或者(‘)表示字符串 | | 数组 | type[]
Array| let list: number[] = [1, 2, 3];
let list: Array= [1, 2, 3]; | | | 元组 | | // 声明一个元组
let x: [string, number];
// 初始化
x = [‘hello’, 10]
console.log(x[0].substr(1));
console.log(x[1]) | 元组可以表示一个已知元素数量和类型的数组,但是初始化的时候元素类型必须和声明时一致 | | 枚举 | enum | enum Color {Red, Green, Blue}
let c: Color = Color.Green | 可以对枚举型中的元素进行手动指定编号 | | | Any | let notSure: any = 4;
let list: any[] = [1, true, ‘free’] | 表示任意类型 | | | Void | | 表示没有任何类型 | | | Object |
| 表示非原始类型,not (number, string, boolean, null, symbol, undedined) |
类型断言
- let someValue: any = ‘this is a string’;
- ‘尖括号’语法
- let strLength: number = (
someValue).length;
- let strLength: number = (
- ‘as’语法:
- let strLength: number = (someValue as string).length;
变量声明
- let声明
- let hello = ‘Hello’;
- 块作用域
- const声明
- 通过const声明的变量在赋值后不能再改变
- let声明