二次封装LocalStorage,添加ts类型支持

 使用效果:良好的ts类型推断,良好的代码提示:

/**本地存储的数据 */
interface LocalhostData {
    /**用户token */
    token: string,
    /**xxxx模块的数据,是一个数字数组 */
    test1: number[],
    /**xxxx模块的数据,是一个字符串数组 */
    test2: string[]
} 
/**本地存储的键值 */
type key = Extract<keyof LocalhostData, string>
/**二次封装的本地存储,添加ts类型支持 */
const localStore  =  {
    /**获取数据。会从JSON转回对象。如果localStorage中没有该值,则将返回null */
    getItem<D extends key>(key: D): LocalhostData[D] | null {
        const data = localStorage.getItem(key) || "null"//这样JSON.parse解析出来的就是null
        try {
            const res = JSON.parse(data) as LocalhostData[D]
            return res
        } catch (error) {//如果出现报错,那么就返回原数据
            console.error('getItem出错', error)
            return data as LocalhostData[D]
        }
    },
    /**设置数据。会帮忙把对象转为JSON存储 */
    setItem<D extends key>(key: D, value: LocalhostData[D]) {
        if (!key || value == undefined) {
            console.log('setItem - 请传递正确的参数');
            return
        }
        localStorage.setItem(key, JSON.stringify(value))
    },
    /**移除数据 */
    removeItem(key: key) {
        localStorage.removeItem(key)
    }
} 
export default localStore

还有一些,比如clear清除全部,这些没啥好类型推断的,就没封装进来了

猜你喜欢

转载自blog.csdn.net/m0_64130892/article/details/133205643
今日推荐