这是我参与「第四届青训营 」笔记创作活动的第7天
一.什么是TypeScript
1.TypeScript的发展历史
- 2012-10:微软发布了TypeScript的第一个版本
- 2014-10:Angular发布了基于TypeScript的2.0版本
- 2015-04:微软发布了Visual Studio Code
- 2016-05:@types/react发布,TypeScript可开发React
- 2020-09:Vue发布了3.0版本
- 2021-11:v4.5版本发布
2.为什么选择TypeScript
静态类型:
- 可读性增强:基于语法解析TSDoc,ide增强
- 可维护性增强:在编译阶段暴露大部分错误
- 多人合作的大型项目中,获得更好的稳定性和开发效率
JS的超集:
- 包含于兼容所有js特性,支持共存
- 支持渐进式引入与升级
3.推荐浏览器
VSCode
二.基本语法
1.基础数据类型
2.对象数据类型
interface IBytedancer{
//只读属性:约束属性不可在对象初始化以外赋值
readonly jobld:number;
name:string;
sex:'man' | 'woamn' | 'other';
age:number:
//可选属性:定义该属性可以不存在
hobby?:string;
//任意属性:约束所有对象属性都必须是该属性的子类型
[key: string]: any;
}
3.函数类型
js的函数
function add(x,y){
return x+y;
}
const mult=(x,y)=>x*y;
ts的函数
function add(x:number,y:number):number{
return x+y;
}
const mult:(x:number,y:number)=>number=(x,y)=>x*y;
ts支持通过借口定义类型
interface IMult{
(x:number,y:number):number;
}
const mult:IMult=(x,y)=>x*y;
函数的重载
//对getDate函数进行重载,timestamp为可缺省参数
function getDate(type:'string',timestamp?:string): string;
function getDate(type:'date',timestamp?:string): Date;
function getDate(type:'string' | 'date',timestamp?:string):Date | string;
const date = new Date(timestamp);
return type == 'string' ? date.toLocaleString():date;
}
const x = getDate('date'); //x:Date
const y = getDate('string','2018-01-10');//y:string
5.数组类型
6.Typescript补充类型
7.Typescript泛型
8.类型别名&类型断言
9.字符串/数字 字面量
三.高级类型
1.联合/交叉类型
使用js
//为书籍列表编写类型
const bookList=[{
author:'xiaoming',
type:'history',
range:'2001-2021',
},{
author:'xiaoli',
type:'story',
theme:'love',
}]
//类型声明繁琐,存在较多重复
interface IHistoryBook{
author:string;
type:string;
range:string;
}
interface IStoryBook{
author:string;
type:streing;
theme:string;
}
type IBookList=Array<IHistoryBook | IStoryBook>;
改进(使用联合交叉)
- 联合类型: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;
})>
2.类型保护与类型守卫
interface IA{a:1,a1:2}
interface IB{b:1,b1:2}
function log(arg: IA | IB){
//报错,类型“IA IB”上不存在属性a,类型IB上不存在属性a
//结论:访问联合类型时,处于程序安全,仅能访问联合类型中的交集部分
if(arg.a){
console.log(arg.a1);
}else{
console.log(arg.b1);
}
}
在js可以运行,但是在ts会报错
改造:
interface IA{a:1,a1:2}
interface IB{b:1,b1:2}
//类型守卫:定义一个函数,他的返回值是一个类型谓词,生效范围为子作用域
function getIsIA(arg: IA | IB):arg is IA{
return !!(arg as IA).a;
}
unction log2(arg: IA | IB){
if(getIsIA(arg)){
console.log(arg.a1);
}else{
console.log(arg.b1);
}
}