这是我参与11月更文挑战的第23天,活动详情查看:2021最后一次更文挑战
TIP 👉 英雄者,胸怀大志,腹有良策,有包藏宇宙之机,吞吐天地之志者也。——《三国演义》
前言
实战
- 你觉得使用ts的好处是什么?
1.1 TypeScript是JavaScript的加强版,它给JavaScript添加了可选的静态类型和基于类的面向对象编程,它拓展了JavaScript的语法。所以ts的功能比js只多不少. 1.2 Typescript 是纯面向对象的编程语言,包含类和接口的概念. 1.3 TS 在开发时就能给出编译错误, 而 JS 错误则需要在运行时才能暴露。 1.4 作为强类型语言,你可以明确知道数据的类型。代码可读性极强,几乎每个人都能理解。 1.5 ts中有很多很方便的特性, 比如可选链.
- type 和 interface的异同
重点:用interface描述数据结构,用type描述类型
2.1 都可以描述一个对象或者函数
interface User {
name: string
age: number
}
interface SetUser {
(name: string, age: number): void;
}
type User = {
name: string
age: number
};
type SetUser = (name: string, age: number)=> void;
2.2 都允许拓展(extends) interface 和 type 都可以拓展,并且两者并不是相互独立的,也就是说 interface 可以 extends type, type 也可以 extends interface 。 虽然效果差不多,但是两者语法不同。
// interface extends interface
interface Name {
name: string;
}
interface User extends Name {
age: number;
}
// type extends type
type Name = {
name: string;
}
type User = Name & { age: number };
// interface extends type
type Name = {
name: string;
}
interface User extends Name {
age: number;
}
// type extends interface
interface Name {
name: string;
}
type User = Name & {
age: number;
}
2.3 只有type可以做的
type 可以声明基本类型别名,联合类型,元组等类型
// 基本类型别名
type Name = string
// 联合类型
interface Dog {
wong();
}
interface Cat {
miao();
}
type Pet = Dog | Cat
// 具体定义数组每个位置的类型
type PetList = [Dog, Pet]
// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type B = typeof div
- 如何基于一个已有类型, 扩展出一个大部分内容相似, 但是有部分区别的类型?
首先可以通过Pick和Omit
interface Test {
name: string;
sex: number;
height: string;
}
type Sex = Pick<Test, 'sex'>;
const a: Sex = { sex: 1 };
type WithoutSex = Omit<Test, 'sex'>;
const b: WithoutSex = { name: '1111', height: 'sss' };
比如Partial, Required.
再者可以通过泛型.
- 什么是泛型, 泛型的具体使用?
泛型是指在定义函数、接口或类的时候,不预先指定具体的类型,使用时再去指定类型的一种特性。
可以把泛型理解为代表类型的参数
interface Test<T = any> {
userId: T;
}
type TestA = Test<string>;
type TestB = Test<number>;
const a: TestA = {
userId: '111',
};
const b: TestB = {
userId: 2222,
};
-
实现一个基于ts和事件模式的countdown基础类
import { EventEmitter } from 'eventemitter3';
export interface RemainTimeData {
/** 天数 */
days: number;
/**
* 小时数
*/
hours: number;
/**
* 分钟数
*/
minutes: number;
/**
* 秒数
*/
seconds: number;
/**
* 毫秒数
*/
count: number;
}
export type CountdownCallback = (remainTimeData: RemainTimeData, remainTime: number) => void;
enum CountdownStatus {
running,
paused,
stoped,
}
export enum CountdownEventName {
START = 'start',
STOP = 'stop',
RUNNING = 'running',
}
interface CountdownEventMap {
[CountdownEventName.START]: [];
[CountdownEventName.STOP]: [];
[CountdownEventName.RUNNING]: [RemainTimeData, number];
}
export function fillZero(num: number) {
return `0${num}`.slice(-2);
}
export class Countdown extends EventEmitter<CountdownEventMap> {
private static COUNT_IN_MILLISECOND: number = 1 * 100;
private static SECOND_IN_MILLISECOND: number = 10 * Countdown.COUNT_IN_MILLISECOND;
private static MINUTE_IN_MILLISECOND: number = 60 * Countdown.SECOND_IN_MILLISECOND;
private static HOUR_IN_MILLISECOND: number = 60 * Countdown.MINUTE_IN_MILLISECOND;
private static DAY_IN_MILLISECOND: number = 24 * Countdown.HOUR_IN_MILLISECOND;
private endTime: number;
private remainTime: number = 0;
private status: CountdownStatus = CountdownStatus.stoped;
private step: number;
constructor(endTime: number, step: number = 1e3) {
super();
this.endTime = endTime;
this.step = step;
this.start();
}
public start() {
this.emit(CountdownEventName.START);
this.status = CountdownStatus.running;
this.countdown();
}
public stop() {
this.emit(CountdownEventName.STOP);
this.status = CountdownStatus.stoped;
}
private countdown() {
if (this.status !== CountdownStatus.running) {
return;
}
this.remainTime = Math.max(this.endTime - Date.now(), 0);
this.emit(CountdownEventName.RUNNING, this.parseRemainTime(this.remainTime), this.remainTime);
if (this.remainTime > 0) {
setTimeout(() => this.countdown(), this.step);
} else {
this.stop();
}
}
private parseRemainTime(remainTime: number): RemainTimeData {
let time = remainTime;
const days = Math.floor(time / Countdown.DAY_IN_MILLISECOND);
time = time % Countdown.DAY_IN_MILLISECOND;
const hours = Math.floor(time / Countdown.HOUR_IN_MILLISECOND);
time = time % Countdown.HOUR_IN_MILLISECOND;
const minutes = Math.floor(time / Countdown.MINUTE_IN_MILLISECOND);
time = time % Countdown.MINUTE_IN_MILLISECOND;
const seconds = Math.floor(time / Countdown.SECOND_IN_MILLISECOND);
time = time % Countdown.SECOND_IN_MILLISECOND;
const count = Math.floor(time / Countdown.COUNT_IN_MILLISECOND);
return {
days,
hours,
minutes,
seconds,
count,
};
}
}
-
写一个缓存的装饰器
const cacheMap = new Map();
export function EnableCache(target: any, name: string, descriptor: PropertyDescriptor) {
const val = descriptor.value;
descriptor.value = async function(...args: any) {
const cacheKey = name + JSON.stringify(args);
if (!cacheMap.get(cacheKey)) {
const cacheValue = Promise.resolve(val.apply(this, args)).catch((_) => cacheMap.set(cacheKey, null));
cacheMap.set(cacheKey, cacheValue);
}
return cacheMap.get(cacheKey);
};
return descriptor;
}
「欢迎在评论区讨论」