From ec0f1ba33d029db0e035b472105f24a008ea40c6 Mon Sep 17 00:00:00 2001 From: AuroraTea <1352685369@qq.com> Date: Wed, 20 Mar 2024 21:05:35 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A8=20overload=20in=20ts=20&=20avoid?= =?UTF-8?q?=20assertion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It appears to be repeating itself, but in reality, one is taking CookieOptions & {readonly: true;} as input and returning Readonly>, while the other is taking CookieOptions & {readonly: true;} as input and returning CookieRef. This way, it aligns with the appropriate overload call pattern. --- packages/nuxt/src/runtime/storages.ts | 39 ++++++++++++++++++--------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/packages/nuxt/src/runtime/storages.ts b/packages/nuxt/src/runtime/storages.ts index 2ce51b7..86db882 100644 --- a/packages/nuxt/src/runtime/storages.ts +++ b/packages/nuxt/src/runtime/storages.ts @@ -1,26 +1,39 @@ import type { StorageLike } from 'pinia-plugin-persistedstate' import { type CookieOptions, useCookie, useNuxtApp } from '#app' -function usePersistedstateCookies(cookieOptions?: Omit, 'encode' | 'decode'>) { +function usePersistedstateCookies( + cookieOptions?: Omit, 'encode' | 'decode'>, +): StorageLike { return ({ - getItem: (key) => { - return useCookie(key, { - ...cookieOptions, - encode: encodeURIComponent, - decode: decodeURIComponent, - }).value - }, + getItem: key => + cookieOptions?.readonly + ? useCookie(key, { + ...cookieOptions, + encode: encodeURIComponent, + decode: decodeURIComponent, + readonly: true, + }).value + : useCookie(key, { + ...cookieOptions, + encode: encodeURIComponent, + decode: decodeURIComponent, + readonly: false, + }).value, setItem: (key, value) => { + if (cookieOptions?.readonly) + throw new Error('Cannot set a readonly cookie.') + useCookie(key, { ...cookieOptions, encode: encodeURIComponent, decode: decodeURIComponent, + readonly: false, }).value = value }, - }) as StorageLike + }) } -function usePersistedstateLocalStorage() { +function usePersistedstateLocalStorage(): StorageLike { return ({ getItem: (key) => { return !useNuxtApp().ssrContext @@ -31,10 +44,10 @@ function usePersistedstateLocalStorage() { if (!useNuxtApp().ssrContext) localStorage.setItem(key, value) }, - }) as StorageLike + }) } -function usePersistedstateSessionStorage() { +function usePersistedstateSessionStorage(): StorageLike { return ({ getItem: (key) => { return !useNuxtApp().ssrContext @@ -45,7 +58,7 @@ function usePersistedstateSessionStorage() { if (!useNuxtApp().ssrContext) sessionStorage.setItem(key, value) }, - }) as StorageLike + }) } export const persistedState = {