这是我参与「第四届青训营 」笔记创作活动的第23天
TypeScript
Js与Ts的区别
JS
- 动态类型
- 弱类型语言
TS - 静态类型
- 弱类型语言
优点 - 可读性增强:基于语法解解析TSDoc,ide增强
- 可维护性增强:在编译阶段暴露大部分错误
- 包含于兼容所有Js特性,支持共存
- 支持渐进式引入和升级
总结:多人合作的大型项目中,获得更好的稳定性和开发效率。
基础数据类型
const q: string ='string' //字符串
const w: number = 1; //数字
const e: boolean =true //布尔值
const r: null =null //null
const t: undefined = undefined //undefined
对象类型
interface IBytedancer { //声明对象类型
readonly jobId: number; //只读属性:约束属性不可在对象初始化外赋值
name: string;
sex: 'man' | 'woman' | 'other';
age: number;
hobby?:string; //可选属性:定义该属性可以不存在
[key:string]:any;//任意属性:约束所有对象属性都必须是该属性的子类型
}
const bytedancer:IBytedancer = {
jobID: 9303245,
name: 'Lin',
sex: 'man',
age: 28,
hobby: 'swimming'
}
bytedancer.jobId = 12345; //报错:无法分配到“jobId”,因为他只是只读属性
bytedancer.plateform ='data';//成功:任意属性标注下可以添加任意属性
const bytedancer2:IBytedancer={//报错:缺少属性“name”,hobby可缺省
jobId:89757,
sex: 'woman',
age: 18,
}
函数类型
function add(x:number,y:number):number{
return x+y;
}
const mult:(x:number,y:number)=>number =(x,y)=>x*y;
interface IMult {
(x:number,y:number):number;
}
const mult:IMult =(x,y) =>x*y;
函数重载
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
数组类型
type IArr1 = number[]; //类型+方括号
type IArr2 = Array < string | number | Record < string , number >>; //泛型表示
type IArr3 = [ number , number , string , string ]; //元组表示
interface IArr4 {
[key: number]:any;
} //接口表示
const arr1: IArr1=[1,2,3,4,5,6];
const arr2: IArr2=[1,2,'3','4',{a:1}];
const arr3: IArr3=[1,2,'3','4'];
const arr4: IArr4=['string',()=>null,{},[]];