TypeScript入门| 青训营笔记
这是我参与「第四届青训营 」笔记创作活动的的第7天
什么是TypeScript
TypeScript发展历史
- 2012-10:微软发布了 TypeScript 第一个版本(0.8)
- 2014-10:Angular发布了基于 TypeSctipt第一个版本(0.8)
- 2015-04:微软发布了Visual Studio Code
- 2016-05:@types/react发布,TypeScript可开发React
- 2020-09:Vue发布了3.0版本,官方支持TypeScript
- 2021-11:V4.5版本
静态类型
- 可读性增强:基于语法解析TSDoc,ide增强
- 可维护性增强:在编译阶段暴露大部分错误 => 多人合作大项目中,获得更好的稳定性和开发效率
JS的超集
- 包含于兼容所有JS特效,支持共存
- 支持渐进式引入与升级
基本语法
基本数据类型
const q = 'string';/*字符串*/
const w = 1;/*数字*/
const e = true;/*布尔值*/
const r = null;/*null*/
const t = undefined;/*undefined*/
对象类型
const bytedancer: IBytedancer = {
jobId: 93032,
name:'wang',
sex:'man',
aga:'21',
hobby:'swimming',
函数类型
function add(x,y){
return x + y;
}
const mult = (x,y) => x * y;
数组类型
类型+方括号 表示
type IArr1 = number[];
泛型表示
type IArr2 = Array<string | number | Record<string, number>>;
元祖表示
type IArr3 = [number, number, string, string];
接口表示
interface IArr4 {
[key: number]: any;
}
const arr1: IArry1 = [1,2,3];
const arr2: IArry2 = [1,2,'3'];
const arr3: IArry3 = [1,2,'3',{ a: 1 }];
const arr4: IArry4 = ['string',() => null,{},[]];
字符串/数字 字面量
允许定义字符串/数字必须的固定值
IDomtag必须为html、body、div、span中的其一
type IDomTag = 'html' | 'body' | 'div' | 'span';
IOddNumber必须为1、3、5、7、9中的其一
type IOddNumber = 1 | 3 | 5 | 7 | 9;
高级类型
联合/交叉类型
- 联合类型:IA|IB;联合类型表示一个值可以是几种类型之一
- 交叉类型:IA&IB:多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性
const bookList = [{
author:'xiaoming',
type:'history',
range:'2001-2021',
},{
author:'xiaoli',
type:'story',
theme:'love',
}]
type IBookList = Array<{
author: string;
} & ({
type: 'history';
range: string;
} | {
type: 'story';
theme: string;
})>
类型保护与类型守卫
itnerface IA { a: 1, a1: 2}
itnerface IB { B: 1, B1: 2}
/*类型守卫:定义一个函数,它的返回值是一个类型谓词,生效范围为子作用域*/
function getIsIA(arg: IA | IB): arg is IA {
return !!(arg as IA).a;
}
function log2(arg: IA | IB) {
if(getIsIA(arg)) {
console.log(arg.a1)
} else {
console.log(arg.b1);
}
}
实现函数reverse
实现函数logBook类型
函数接受书本类型,并logger出相关特征
function logBook(book: IBookItem){
//联合类型+类型保护 = 自动类行推断
if(book.type === 'history'){
console.log(book.range)
}
else{
console.log(book.theme):
}
}
工程应用
Typescript工程应用 - Web
2.配置tsconfig.js文件
3.运行webpack启动/打包
4.loader处理ts文件时,会进行编译与类型检查
Typescript工程应用 - Node
使用TSC编译
1.安装Node与npm
2.配置tsconfig.js
3.使用npm安装tsc
4.使用tsc运行编译得到js文件
总结
经过今天的学习,初步了解了TypeScript,发现它与JavaScript有许多相似之处,就因为这些相似的地方,就能让我更快的去理解它,去掌握它,我相信通过一点一点的学习,我们都会有很大的进步的。
学到这我想大家也对Typescript有了初步的认识了吧,不如现在就开始动手练习练习吧
如果你有任何建议都可以在评论区留言,或发电子邮箱,欢迎大家评论留言(ˆ⌣ˆ)
作者:Yifan
日期:2022年7月24日
电子邮箱:1279640748@qq.com