这是我参与「第四届青训营 」笔记创作活动的第7天
一、什么是Typescript
1.1 Typescript的发展
1.2 Typescript的特点
静态类型
- 可读性增强:基于语法解析TSDoc,ide增强
- 可维护性增强:在编译阶段暴露大部分错误 => 多人合作的大型项目中,获得更好的稳定性和开发效率
JS的超集
- 包含于兼容所有的Jscript特性,支持共存
- 支持渐进式引入与升级
二、Typescript 基本语法
2.1 基础数据类型
/* 字符串 */
const q: string='string'
/* 数字 */
const w: number = 1;
/* 布尔值 */
const e: boolean = true;
/* null */
const r: null = null;
/* nuderfined */
const t: underfined = underfined;
2.2 对象类型
interface IBytedancer{
/*只读属性:约束属性不可在对象初始化外赋值*/
readonly jobId: number;
name: string;
sex: 'man'|'woman'|'other';
age: number;
/*可选属性:定义该属性可以不存在*/
habby ?: string;
/*任意属性:约束所有对象属性都必须时该属性的子类型*/
[key: string]: any;
}
2.3 函数类型
2.4 数组类型
2.5 Typescript补充类型
2.6 类型别名&类型断言
类型别名:
/* 通过type关键字定义了IObjArr的别名类型 */
type IObjArr = Array<{
key: string;
[objKey: string]: any;
}>
类型断言:
function KeyBy<T extends IObjArr>(objArr: Array<T>){
/* 为指定类型时,result类型为{} */
const result = objArr.reduce((res,val,key) => {
res[key] = val;
return res;
},{});
/* 通过as关键字,断言result类型为 正确类型 */
return result as Record<string,T>;
}
2.7 字符串/数字 字面量
/* 允许指定字符串/数字必须的固定值 */
/* IDomTag必须为 html、body、div、span 中的其一 */
type IDomTag = 'html'|'body'|'div'|'span';
/* IOddNumber必须为1、3、5、7、9中的其一 */
type IOddNumber = 1 | 3 | 5 | 7 | 9;
三、高级类型
3.1联合/交叉类型
-
联合类型:IA | IB;联合类型表示一个值可以是几种类型之一
-
交叉类型:IA & IB;多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性
3.2 类型保护和类型守卫
类型保护:访问联合类型时,出于程序安全,仅能访问联合类型中的交集部分
例如:对于以下代码:
interface IA { a: 1 , A1: 2}
interface IB { b: 1 , b1: 2}
function log(arg: IA | IB){
if(arg.a){
console.log(arg.a1);
}else{
console.log(arg.b1);
}
}
其运行结果会报错,因为类型"IA | IB"上不存在属性"a",类型"IB"上不存在属性"a"。
typeof类型保护
function reverse(target:string | Array<any>){
if(typeof target === 'string'){
return target.split('').reverse().join('');
}
instance类型保护
function reverse(target:string | Array<any>){
if(target instanceof Object){
return target.reverse();
}
类型守卫:定义一个函数,它的返回值是一个类型谓词,生效范围为子作用域
例如:
3.3 高级类型
- 索引类型:关键字【keyof】,其相当于取值对象中的所有key组成的字符串字面量,如:
type IKeys = keyof { a: string; b: number }; // => type IKeys = "a"|"b"
-
关键字【in】:相当于取值字符串字面量中的一种可能,配合泛型p,即表示 每个key
-
关键字【?】:通过设定对象可选选项,即可自动推导出子级类型
3.4 函数返回值类型
- 实现函数delayCall的类型声明:
- 关键字【extends】 跟随泛型出现时,表示类型推断,其表达可类比三元表达式,如: T === 判断类型 ?类型A :类型B
- 关键字【infer】 出现在类型推荐中,表示定义类型变量,可以用于指代类型。
四、工程应用
Typescript工程应用方面主要有两部分:浏览器Web、NodeJS。
五、个人总结
这是我在青训营学习的第9天,今天主要学习了Typescript的基础知识,包括从什么是Typescript、Typescript的发展到Typescript的基本语法内容、高级类型的学习。结合Javascript与Typescript的关系以及不同,可以快速入门Typescript。