今天是我参与「第五届青训营 」伴学笔记创作活动的第 15 天.
TypeScript优点
- ·可读性增强:基于语法解析TSDoc,ide增强
- ·可维护性增强:在编译阶段暴露大部分错误 多人合作的大型项目中,获得更好的稳定性和开发效率
- ·包含于兼容所有Js特性,支持共存 JS的超集
- ·支持渐进式引入与升级
基础数据类型
包括字符串,数字,布尔值等
/*字符串 */
const q= 'string' ;/*数字*/
const w= 1;/*布尔值*/
const e = true;
/* null */
const r = null;/*undefined */
const t = undefined;
/*字符串*/
const q: strina - 'c+ui.l.-0862/*数字*/
const w: numk./*布尔值*/
const e: boolean = true;
/* null */
const r: null = null;/* undefined */
const t: undefined = undefined;
对象类型
包括只读属性,可选属性,任意属性
const bytedancer: IBytedancer = ijobId: 9303245,
name: 'Lin ' ,
sex: 'man ' ,
age: 28,
hobby: 'swimming' ,}
interface IBytedancer {
/*只读属性:约束属性不可在对象初始化外赋值*/
readonly jobId:number;
name: string;
sex: 'man' l 'woman' l 'other' ;
age: number;
/*可选属性:定义该属性可以不存在*/hobby?: string;
/*任意属性:约束所有对象属性都必须是该属性的子类型*/[key: string]: any;
}
函数重载
对getDate函数进行重载,timestamp为可缺省参数
不能将类型"(type: any,timestamp: any) = strina l Date"分配给类刑"TGetDate"
不能将类型"string | Date"分配给类型“string"。
不能将类型“Date"分配给类型“string"。
function getDate(type: 'string ' , timestamp?: string): string
interface IGetDate {
(type: 'string ' , timestamp?: string): string;
(type: 'date', timestamp?: string): Date;
(type: 'string' l 'date ', timestamp?: string): Date | string;
}
const getDate2: IGetDate = (type,timestamp) => {
const date = new Date(timestamp);
return type a= 'string' ? date.toLocaleString() : date;
}
联合/交叉类型
- ·联合类型:IA|IB;联合类型表示一个值可以是几种类型之一
- ·交叉类型: IA&IB;多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性
interface lHistoryBook {
author: string;
type: string;
range: string
}
interface lStoryBook {
author: string;
type: string;theme: string;
}
type lBookList = Array<lHistoryBook | IStoryBook>;
高级类型
interface lSourceObj {x?: string;
y?: strina;
}
interface lTargetObj {
x: string;
y: string
}
type IlMerge = (sourceObj: ISourceObj, targetObj: ITargetObj)=>lTargetObj;
类型实现繁琐:若obj类型较为复杂,则声明source和target便需要大量重复2遍,容易出错:若target增加/减少key,则需要source联动去除
函数返回值类型
类型实现繁琐:若obj类型较为复杂,则声明source和target便需要大量重复2遍,容易出错:若target增加/减少key,则需要source联动去除
type lDelayCall = <T extends (0 => any>(func: T) => ReturnType<T>;
type lReturnType<T extends (..args: any) =>any> = T extends (..args: any) => infer R ?R : any
关键字【extends】跟随泛型出现时,表示类型推断,其表达可类比三元表达式1/如T===判断类型?类型A:类型B
关键字【infer】出现在类型推荐中,表示定义类型变量,可以用于指代类型
如该场景下,将函数的返回值类型作为变量,使用新泛型R表示,使用在类型推荐命中的结果中