typescript用localStorage封装过期时间
# ts用localStorage封装过期时间设置
# 思考
在我们使用cookie的时候是可以设置过期时间,但是localStorage本身是没有该机制的,只能人为手动删除,否则会一直存放在浏览器当中,可不可以根cookie一样设置一个有效时间,一直存在浏览器当中感觉有点浪费,我们可以把localStorage进行二次封装
# 实现思路
- 存储时候设置一个过期时间
- 存储的数据进行格式化方便同意管理
- 获取当前时间进行判断是否过期,过期进行删除
# 代码实现
# 定义枚举
export enum TimeType {
expire = '_expire', // 过期时间key
permament = '_permament' // 永久不过期
}
1
2
3
4
2
3
4
# type ts定义
import { TimeType } from './enum'
export type key = string // key类型
export type expire = TimeType.permament | number
export interface Data<T> {
value: T,
[TimeType.expire]: TimeType.expire | number
}
export interface Result<T> {
message: string,
value: T | null
}
// 用class方法约束
export interface StoregeClass {
set: <T>(key: Key, value: T, expire: expire) => void
get: <T>(key: Key) => Result<T | null>
remove: (key: Key) => void
clear: () => void
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2024/01/20, 21:01:00