一、为什么要用ts?
1)ts是js的加强版,它给js增加了可选的静态类型和面向对象编程,它的功能比js只多不少。
2)ts是面向对象的语言,它包含类和接口的概念;
3)ts在开发时就能给出编译错误,而js需要运行时才能发现;
4)ts作为强类型语言,明确数据类型,代码可读性比较强;
5)ts中有很多很方便的特性比如可选链。
二、
1、基础类型:number,string,array,boolean,object
定义a为number类型,且给它赋值1。
let A :number = 1;
2、枚举 enum
enum Status {
START = 'start',//若没有赋值,则默认1,2,3...这样
STOP = 'stop',
}
const a = Status.START;
3、type/interface 定义特定对象结构等
type UserInfo= {
name:string;
grade:number;
}
interface UserInfo {
name:string;
grade?:number;//问号表示可填可不填
}
4、联合类型|(一次一种类型)
interface UserInfoA {
name:string;
year:number;
}
interface UserInfoB {
height:number;
}
function test(param: UserInfoA|UserInfoB)//参数必须事其中之一
5、交叉类型&(两个或多个的合并类型)
interface UserInfoA {
name:string;
year:number;
}
interface UserInfoB {
height:number;
}
function test(param: UserInfoA&UserInfoB)//参数必须事这两个类型的并集
5、typeof 用来获取一个变量声明或对象类型
typeof 'a' = 'string';//true
function toArray(x: number):Array<number>
{return [x]}
type y = typeof toArray;//y为(x:number)=>number[]
6、keyof操作符可以用来获取对象中的所有key值
interface UserInfoA {
name:string;
year:number;
}
type a = keyof UserInfoA;//只能是‘name’和‘year’
const b :a = 'name';
const c:a = 'year';//只能赋值这两个不然会报错
7、in 用来遍历枚举类型
type keys = 'a'|'b'|'c';
type b = {
[key in keys] :any;
}//b最后为{a:any;b:any;c:any}
8、extends 继承,通常用来做泛型约束,即定义的泛型继承一个类型
interface User {
name:string;
}
function test<T extends User>(params:T):T{
return params;
}
test(1);//会报错
test({name:'sss',value:1})//正确
9、Paritial Paritial把某个类型里的属性全部变成可选项?
interface User {
name:string;
}
type B = Paritial<User>//以后b的属性name可填可不填
10、Required Required就是将某个类型里的所有属性变成必填项
11、Readonly Readonly将所有属性变成可读,不可写,即不可以被重新赋值修改
12、Record
interface PageInfo{
title:string;
}
type page = 'a'|'b'|'c';
type mix = Record<PageInfo,page>;
const a :mix = {
'a':{title:'xxx'},
'b':{title:'xxx'},
'c':{title:'xxx'}
}
13、Exclude
type a = Exclude<'a'|'b'|'c','a'>//只剩下‘b’|'c'
type b = Exclude<'a'|'b'|'c','a'|'b'>//只剩下‘c’
14、Extract
type a = Extract<'a'|'b'|'c','b'|'c'>//'b'|'c'
type b = Extract<string|number|(()=>void),Function>//交集是函数,因为()=>void是函数的一种,所以结果是()=>void
三、简单的装饰器(通过装饰器的写法去修改原有逻辑,不修改原有的代码)
1、计算函数执行时间
export function measure(target:any,name:any,descriptor:any){
const val = descriptor.value;
descriptor.value = async function(){
const starttime = Date.now();
//this指向不改变,普通函数this指向调用它的对象实例
const value = await val.apply(this,arguments);
console.log('执行时间为'+Date.now()-starttime);
return value;
}
return descriptor;
}
//使用
@measure
// 写在要计算的那个方法前面
2、缓存
let map = new Map();
export function autoCache(target:any,name:any,descriptor:propertyDescriptor){
const val = descriptor.value;
descriptor.value = async function(...args:any){
const key = name+JSON.stringfy(args);
let value;
if(!map.get(key)){
//这里用一个promise包裹返回的值,在cache里能在返回失败的时候清空原来的值,这里的promise.resolve只是为了包一层,如果传入的值是promise实例则直接使用,如果不是则包一层正常执行resolve的promise实例返回,这样就都能使用.then链式调用来执行正确和错误方法了
//这种方式刷新就没了,它是存在内存中的
value = await Promise.resolve(val.apply(this,args)).catch((_)=>map.set(key,null));
}
map.set(key,value)
return map.get(key);
}
return descriptor;
}
//使用
@autoCache
// 写在要重新请求的那个方法前面
四、通过几个小实例来了解ts写法
1、封装路由跳转约束跳转参数
import { Dictionary } from "vue-router/types/router";
import Router from "../router";
export type BaseRouteType = Dictionary<string>;
export enum routerPath {
index = '/index',
home = '/',
}
export interface indexParam extends BaseRouteType {
userName:string,
}
export interface homeParam extends BaseRouteType {
name:string,
}
export interface routerParams {
[routerPath.index]:indexParam;
[routerPath.home]:homeParam;
}
export class routerHelper {
public static replace<T extends routerPath>(path: T,params: routerParams[T]) {
Router.replace({
path:path,
params:params,
})
}
public static push<T extends routerPath>(path:routerPath, params: routerParams[T]) {
Router.push({
path:path,
params:params,
})
}
}
//这时要跳转对应的路径一定需要包含对应的参数,不然在开发编译时就会报错
/比如
routerHelper.push(routerPath.index,{userName:'qqqq'})
2、倒计时
export enum countDownStatus {
runing,
paused,
stoped,
}
export enum countDownEventName {
START='start',
STOP='stop',
RUNNING='running',
}
export interface remianTimeData {
days:number,
hours:number,
minutes:number,
seconds:number,
count:number,
}
export interface countDownMap {
[countDownEventName.RUNNING]: [remianTimeData,number],
[countDownEventName.START]: [];
[countDownEventName.STOP]: [];
}
export class countDown extends EventEmitter<countDownMap>{
private static COUNT:number = 100;
private static SECONDS:number = 10*countDown.COUNT;
private static MINUTES:number = 60*countDown.SECONDS;
private static HOURS:number = 60*countDown.MINUTES;
private static DAYS:number = 24*countDown.HOURS;
private endTime: number;
private step: number;
private status:countDownStatus = countDownStatus.stoped;
private remianTime: number = 0;
constructor(time:number, step: number) {
super();
this.endTime = time;
this.step = step;
this.startCount();
}
public startCount() {
this.emit(countDownEventName.START);
this.status = countDownStatus.runing
this.countTime();
}
public countTime(){
if(this.status !== countDownStatus.runing){
return;
}
this.remianTime = Math.max(this.endTime - Date.now(), 0);
this.emit(countDownEventName.RUNNING, this.fomateTime(this.remianTime),this.remianTime);
if(this.remianTime>0) {
setTimeout(() => {
this.countTime();
}, this.step)
} else {
this.stop();
}
}
public fomateTime(remianTime: number){
let time = remianTime;
const days = time/countDown.DAYS;
time = time%countDown.DAYS;
const hours = time /countDown.HOURS;
time = time%countDown.HOURS;
const minutes = time/countDown.MINUTES;
time = time%countDown.MINUTES;
const seconds = time/countDown.SECONDS
time = time%countDown.SECONDS;
const count = time/countDown.COUNT;
return {days,hours,minutes,seconds,count}
}
public stop(){
this.emit(countDownEventName.STOP);
this.status = countDownStatus.stoped;
}
}
五、interface跟type的区别
同:
1)都可以描述一个对象或函数
//对象
interface a{
name:string,
grade:number
}
type a = {
name:string,
grade:number,
}
//函数
interface b {
(name:string,grade:number):void
}
type b = (name:string,grade:number)=>void
2)都允许扩展extends,且两者之间可以互相扩展
//interface extend
interface a {
name:string
}
interface b extends a{
age:number
}
//type extends
type a = {name:string}
type b = a & {age:number}
//interface extends type
type a = {name:string}
interface b extend a{
age:number
}
//type extends interface
interface a {name:string}
type b = a&{age:number}
不同:只有type可以做的
type可以声明基本类型别名,元组,联合类型等
//基本类型
type a = string;
//联合类型
interface a = {name:string}
interface b = {age:number}
type c = a | b;
//具体定义每个数组的位置类型的叫元组
type c = [a,b]
//获取一个变量类型的时候用typeof
const div = document.getElementByid('id')
type a = typeof div
六:如何基于一个已有类型,扩展出大部分内容相似,但有部分区别的的类型?
1、首先可以通过Pick和Omit
interface test {
name:string,
sex:string,
height:number
}
//pick将Sex里的sex属性类型与test里的sex属性类型一致,如果要修改只需要修改test里的即可
type Sex = Pick<test,'sex'>
const a :Sex = {sex:'女'}
//去掉sex属性
type WithoutSex = Omit<test,'sex'>;
const b :WithoutSex = {name:'11',height:11}
还有partial和required 泛型
泛型是指定义接口,类的时候不具体指定类型,而是等到使用时才指定的一种特性
例如:
interface a <T = any> {name:T}
type b = a<string>
type c = a<number>
const bb:b = {name:'aa'}
const cc:c = {name:12}