我是靠谱客的博主 传统蓝天,这篇文章主要介绍typescript学习1 基础类型,现在分享给大家,希望可以做个参考。

TypeScript支持与JavaScript几乎相同的数据类型,此外还提供了实用的枚举类型方便我们使用。

TypeScript的基础类型有:布尔值、数字字符串数组元组枚举AnyVoidNull和Undefinednever

变量声明方式:  let 变量名:变量类型 = 值

复制代码
1
2
3
4
5
6
7
8
9
let 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:

元组类型允许表示一个已知元素数量和类型的数组,个元素的类型不必相同.

复制代码
1
2
3
let tup:[string,number]; tup = ["str",123]; tup = ['str',false];

编译时报错firstTsc.ts(3,1): error TS2322: Type '[string, boolean]' is not assignable to type '[string, number]'.

  Type 'boolean' is not assignable to type 'number'.

当访问一个越界的元素,会使用联合类型替代 => (个人理解)如果越界,越界元素的类型需要是在元素声明中提到过的元素类型之一.

枚举 enum :

enum类型是对js标准数据类型的一个补充,可以为一组数值赋予友好的名字.

复制代码
1
2
enum color{red,green,blue}; let c:color = color.green; //c=>1

默认为从0开始的索引

复制代码
1
2
3
4
5
6
7
8
9
10
11
enum 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
2
enum color{red=5,green=3,blue=1}; let c:color = color.green; //c => 3

可以通过枚举类型提供的一个枚举值找到他的名字

复制代码
1
2
3
enum 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
2
let list: any[] = [1, true, "free"]; list[1] = 100;

Void:

表示没有任何类型,当一个函数没有返回值时,返回值类型是void

声明一个void类型的变量没有什么大用,因为你只能为它赋予undefinednull

Null和Undefined

Null和Undefined是所有类型的子类型,可以把Null和Undefined赋值给所有类型,但是把其他类型赋值给Null和Undefined就会出错

复制代码
1
2
let 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
2
let someValue: any = "this is a string"; let strLength: number = someValue.length;
)

复制代码
1
2
3
4
5
let 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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部