当前位置:网站首页>[TypeScript] Introduction, Development Environment Construction, Basic Types
[TypeScript] Introduction, Development Environment Construction, Basic Types
2022-07-30 16:10:00 【Eighteen-year-old hates programming】
博客主页:️十八岁讨厌编程️
所属专栏:TypeScript专栏
写文目的:记录学习中的知识点
*目前已更新内容涵盖:【前端】、【后端】、【人工智能】、【数据分析】、【网络爬虫】、【数据结构与算法】、【PS】、【计算机数学】等几个大方面
如果这篇文章对你有帮助,欢迎️关注
、点赞
、收藏
、留言
,看到我会积极回复.
文章目录
TypeScript简介
说到TypeScript我们不得不提到JavaScript,JSIt is a weakly typed dynamic scripting language invented by Netscape.Speaking of weak typing,We also know that it is very flexible,But this flexibility is a double-edged sword.As a result, some errors may not be found at compile time,It doesn't give an error until it runs.This is very detrimental to our later maintenance,And now many large-scale projects of enterprises turn to useTypeScript来解决这个问题.
产生背景:TypeScript 起源于使用JavaScript开发的大型项目 .由于JavaScript语言本身的局限性,难以胜任和维护大型项目开发.因此微软开发了TypeScript ,使得其能够胜任开发大型项目.
TypeScript是微软开发的一个开源的编程语言,通过在JavaScript的基础上添加静态类型定义构建而成.TypeScript通过TypeScript编译器或Babel转译为JavaScript代码,可运行在任何浏览器,任何操作系统.
- TypeScript是JavaScript的超集.
- 它对JS进行了扩展,向JS中引入了类型的概念,并添加了许多新的特性.
- TS代码需要通过编译器编译为JS,然后再交由JS解析器执行.
- TS完全兼容JS,换言之,任何的JS代码都可以直接当成JS使用.
- 相较于JS而言,TS拥有了静态类型,更加严格的语法,更强大的功能;TS可以在代码执行前就完成代码的检查,减小了运行时异常的出现的几率;TS代码可以编译为任意版本的JS代码,可有效解决不同JS运行环境的兼容问题;同样的功能,TS的代码量要大于JS,但由于TS的代码结构更加清晰,变量类型更加明确,在后期代码的维护中TS却远远胜于JS.
TypeScript 开发环境搭建
- 下载Node.js
- 64位:https://nodejs.org/dist/v14.15.1/node-v14.15.1-x64.msi
- 32位:https://nodejs.org/dist/v14.15.1/node-v14.15.1-x86.msi
因为TSCompilation is required to convert toJS,So this time we need oneTS的解析器,而TSThe parser is only usednodejs写的,So this time we have to install itTS的解析器,我们需要先安装nodejs.
左边的LTSstands for long-term maintenance,也就是稳定版
而右边的current代表最新版
- 安装Node.js
在命令行输入node -v进行验证:
- 使用npm全局安装typescript
- 进入命令行
- 输入:npm i -g typescript
npm是node的包管理工具,We can use input at the command linetscto prove that your installation was successful:
- 创建一个ts文件
以ts结尾就行
- 使用tsc对ts文件进行编译
进入命令行
进入ts文件所在目录
执行命令:tsc xxx.ts
结果:
在webstorm中,After you compile successfully,He will show their relationship in a folded way:
基本类型
类型声明
类型声明是TS非常重要的一个特点
通过类型声明可以指定TS中变量(参数、形参)的类型
指定类型后,当为变量赋值时,TS编译器会自动检查值是否符合类型声明,符合则赋值,否则报错
即使报错了,But if it still matchesjs语法,那么tsThe file will still be successfully compiled as js文件
简而言之,类型声明给变量设置了类型,使得变量只能存储某种类型的值
语法:
let 变量: 类型; let 变量: 类型 = 值; function fn(参数: 类型, 参数: 类型): 类型{ ... }
在tsThe number of parameters you pass in is strictly controlled(在js中不会报错):
自动类型判断
- TS拥有自动的类型判断机制
- 当对变量的声明和赋值是同时进行的,TS编译器会自动判断变量的类型
- 所以如果你的变量的声明和赋值时同时进行的,可以省略掉类型声明
// 声明一个变量a,同时指定它的类型为number
let a: number;
// a 的类型设置为了number,在以后的使用过程中a的值只能是数字
a = 10;
a = 33;
// a = 'hello'; // 此行代码会报错,因为变量a的类型是number,不能赋值字符串
let b: string;
b = 'hello';
// b = 123;
// 声明完变量直接进行赋值
// let c: boolean = false;
// 如果变量的声明和赋值是同时进行的,TS可以自动对变量进行类型检测
let c = false;
c = true;
// JS中的函数是不考虑参数的类型和个数的
// function sum(a, b){
// return a + b;
// }
We understand the content after the colon as a qualification on the current variable.
类型
类型:
类型 例子 描述 number 1, -33, 2.5 任意数字 string ‘hi’, “hi”, hi
任意字符串 boolean true、false 布尔值true或false 字面量 其本身 限制变量的值就是该字面量的值 any * 任意类型 unknown * 类型安全的any void 空值(undefined) 没有值(或undefined) never 没有值 不能是任何值 object {name:‘孙悟空’} 任意的JS对象 array [1,2,3] 任意JS数组 tuple [4,5] 元素,TS新增类型,固定长度数组 enum enum{A, B} 枚举,TS中新增类型
number
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;
boolean
let isDone: boolean = false;
string
let color: string = "blue";
color = 'red';
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${
fullName}. I'll be ${
age + 1} years old next month.`;
字面量
也可以使用字面量去指定变量的类型,通过字面量可以确定变量的取值范围
有点js中const的意味
let color: 'red' | 'blue' | 'black'; //colorThe final value obtained can only be generated among these three
let num: 1 | 2 | 3 | 4 | 5;
使用以及注意点:
// 也可以直接使用字面量进行类型声明
let a: 10;
a = 10;
// 可以使用 | 来连接多个类型(联合类型)
let b: "male" | "female";
b = "male";
b = "female";
let c: boolean | string;
c = true;
c = 'hello';
除了可以使用|
之外,我们还可以使用&
:
// &表示同时
let j: {
name: string } & {
age: number };
// j = {name: '孙悟空', age: 18};
any
let d: any = 4;
d = 'hello';
d = true;
使用以及注意点:
// any 表示的是任意类型,一个变量设置类型为any后相当于对该变量关闭了TS的类型检测
// 使用TS时,不建议使用any类型
// let d: any; (显示any)
// 声明变量如果不指定类型,则TS解析器会自动判断变量的类型为any (隐式的any)
let d;
d = 10;
d = 'hello';
d = true;
unknown
let notSure: unknown = 4;
notSure = 'hello';
使用以及注意点:
// unknown 表示未知类型的值
let e: unknown;
e = 10;
e = "hello";
e = true;
let s:string;
// d的类型是any,它可以赋值给任意变量
// s = d;
e = 'hello';
// unknown 实际上就是一个类型安全的any
// unknown类型的变量,不能直接赋值给其他变量
if(typeof e === "string"){
s = e;
}
// 类型断言,可以用来告诉解析器变量的实际类型
/* * 语法: * 变量 as 类型 * <类型>变量 * * */
s = e as string;
s = <string>e;
void
let unusable: void = undefined;
使用以及注意点:
// void 用来表示空,以函数为例,就表示没有返回值的函数
function fn(): void{
}
never
function error(message: string): never {
throw new Error(message);
}
nevermeans nothing is returned,连undefined都没有,So generally used to throw an exception,This type is rarely used.
object
let obj: object = {
};
使用以及注意点:
// object表示一个js对象
let a: object;
a = {
};
a = function () {
};
// {} 用来指定对象中可以包含哪些属性
// 语法:{属性名:属性值,属性名:属性值····} Note that this is strictly satisfied,The specified attribute must have
// 在属性名后边加上?,表示属性是可选的
let b: {
name: string, age?: number};
b = {
name: '孙悟空', age: 18};
// [propName: string]: any 表示任意类型的属性,The number of attributes is not limited at this time
let c: {
name: string, [propName: string]: any};
c = {
name: '猪八戒', age: 18, gender: '男'};
函数结构的类型声明:
/* * 设置函数结构的类型声明: * 语法:(形参:类型, 形参:类型 ...) => 返回值 * */
let d: (a: number ,b: number)=>number;
// d = function (n1: string, n2: string): number{
// return 10;
// }
array
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
使用以及注意点:
/* * 数组的类型声明: * 类型[] * Array<类型> * */
// string[] 表示字符串数组
let e: string[];
e = ['a', 'b', 'c'];
// number[] 表示数值数值
let f: number[];
let g: Array<number>;
g = [1, 2, 3];
tuple
let x: [string, number];
x = ["hello", 10];
使用以及注意点:
/* * 元组,元组就是固定长度的数组 Therefore, the number and type of elements here must be strictly satisfied * 语法:[类型, 类型, 类型] * */
let h: [string, number];
h = ['hello', 123];
enum
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
let c: Color = Color.Green;
类型断言
类型断言
有些情况下,变量的类型对于我们来说是很明确,但是TS编译器却并不清楚,此时,可以通过类型断言来告诉编译器变量的类型,断言有两种形式:
第一种
let someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length;
第二种
let someValue: unknown = "this is a string"; let strLength: number = (<string>someValue).length;
类型别名
Sometimes our type constraints are long,If multiple variables must satisfy this type,Then we can use type aliases at this time.
例如:
// 类型的别名
type myType = 1 | 2 | 3 | 4 | 5;
let k: myType;
let l: myType;
let m: myType;
k = 2;
边栏推荐
猜你喜欢
随机推荐
【AGC】Open Test Example
Flask introductory learning tutorial
Classes and Objects (Part 2)
为什么数据需要序列化
【HMS core】【FAQ】Account、IAP、Location Kit and HarmonyOS典型问题合集1
Pytorch 训练技巧
php如何截取字符串的前几位
PMP每日一练 | 考试不迷路-7.30(包含敏捷+多选)
[HMS core] [FAQ] A collection of typical questions about push kit, analysis services, and video editing services 3
解析字符串拼接的两种情况
游戏窗口化的逆向分析
配置Path环境变量
How to do a good job in technology selection
数组元素逆置
华为ADS获取转化跟踪参数报错:getInstallReferrer IOException: getInstallReferrer not found installreferrer
李沐d2l(七)kaggle房价预测+数值稳定性+模型初始化和激活函数
tiup install
C#西门子S7 协议通过偏移量的方式读写PLC DB块
代码随想录笔记_哈希_1l两数之和
【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常