TypeScript支持与JavaScript几乎相同的数据类型,此外还提供了实用的枚举类型方便我们使用。
TypeScript的基础类型有:布尔值、数字、字符串、数组、元组、枚举、Any、Void、Null和Undefined、never
变量声明方式: let 变量名:变量类型 = 值
复制代码
1
2
3
4
5
6
7
8
9let isDone: boolean = false; //布尔值 let decLiteral: number = 6; //数字 let name: string = "bob"; //字符串,也可以模板字符串let name: string = `Gene`;let sentence: string = `Hello, my name is ${ name }`. let list: number[] = [1, 2, 3]; //数组 let list: Array<number> = [1, 2, 3]; //数组
元组Tuple:
元组类型允许表示一个已知元素数量和类型的数组,个元素的类型不必相同.
复制代码
编译时报错firstTsc.ts(3,1): error TS2322: Type '[string, boolean]' is not assignable to type '[string, number]'.
1
2
3let tup:[string,number]; tup = ["str",123]; tup = ['str',false];
Type 'boolean' is not assignable to type 'number'.
当访问一个越界的元素,会使用联合类型替代 => (个人理解)如果越界,越界元素的类型需要是在元素声明中提到过的元素类型之一.
枚举 enum :
enum类型是对js标准数据类型的一个补充,可以为一组数值赋予友好的名字.
复制代码
默认为从0开始的索引
1
2enum color{red,green,blue}; let c:color = color.green; //c=>1
复制代码
也可以全部手动赋值
1
2
3
4
5
6
7
8
9
10
11enum color{red=1,green,blue}; let c:color = color.green; //c => 2 //编译为 var color; (function (color) { color[color["red"] = 1] = "red"; color[color["green"] = 2] = "green"; color[color["blue"] = 3] = "blue"; })(color || (color = {})); ; var c = color.green;
复制代码
可以通过枚举类型提供的一个枚举值找到他的名字
1
2enum color{red=5,green=3,blue=1}; let c:color = color.green; //c => 3
复制代码
1
2
3enum color{red=5,green=3,blue=1}; let c:color = color.green; //c => 3 let colorName:string = color[1];//colorName => blue
Any:
给不清楚类型的变量指定一个类型.(相当于之前的var???),any类型可以移除类型检查.
Object类型只能赋任意值,但是不能调用值的方法,any类型可以调用值的方法
any还可以定义数组元素数据类型
复制代码
1
2let list: any[] = [1, true, "free"]; list[1] = 100;
Void:
表示没有任何类型,当一个函数没有返回值时,返回值类型是void
声明一个void
类型的变量没有什么大用,因为你只能为它赋予undefined
和null
:
Null和Undefined
Null和Undefined是所有类型的子类型,可以把Null和Undefined赋值给所有类型,但是把其他类型赋值给Null和Undefined就会出错
复制代码
1
2let n: number = undefined;//可以 let u: undefined = 123;//报错 Type '123' is not assignable to type 'undefined'.
Never
表示永不存在的值的类型.是那些抛出异常或者根本就没有返回值的函数的返回值类型
never是所有类型的子类型
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13// 返回never的函数必须存在无法达到的终点 function error(message: string): never { throw new Error(message); } // 推断的返回值类型为never function fail() { return error("Something failed"); } // 返回never的函数必须存在无法达到的终点 function infiniteLoop(): never { while (true) { } }
类型断言:
通过类型段言,可以不进行特殊的数据检查和结构
(
但是我不加也不会报错?????
复制代码
)
1
2let someValue: any = "this is a string"; let strLength: number = someValue.length;
复制代码
1
2
3
4
5let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length;//尖括号写法 //as写法,使用jsx时,必须使用as写法 let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;
最后
以上就是传统蓝天最近收集整理的关于typescript学习1 基础类型的全部内容,更多相关typescript学习1内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复