From 05bc766398b6cbc60fe344c2f57e0ce2d5b2da07 Mon Sep 17 00:00:00 2001 From: Max Duval Date: Thu, 4 Aug 2022 13:52:03 +0100 Subject: [PATCH] fix(storage): return type `unkown` `any` is too loose a value, and consumers should make appropriate decision about the data, so `unknown` is more appropriate. The motivation comes from a bug that made its way into production recently. --- src/storage/storage.ts | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/src/storage/storage.ts b/src/storage/storage.ts index ba0c3c8e..cf31d8ed 100644 --- a/src/storage/storage.ts +++ b/src/storage/storage.ts @@ -1,3 +1,6 @@ +import { isObject } from '../isObject/isObject'; +import { isString } from '../isString/isString'; + class StorageFactory { #storage: Storage | undefined; // https://mdn.io/Private_class_fields @@ -22,27 +25,19 @@ class StorageFactory { return Boolean(this.#storage); } - /* eslint-disable - @typescript-eslint/no-unsafe-assignment, - @typescript-eslint/no-explicit-any, - @typescript-eslint/no-unsafe-argument - -- - - we're using the `try` to handle anything bad happening - - JSON.parse returns an `any`, we really are with an `any` - */ /** * Retrieve an item from storage. * * @param key - the name of the item */ - get(key: string): any { + get(key: string): unknown { try { - const { value, expires } = JSON.parse( - this.#storage?.getItem(key) ?? '', - ); + const data: unknown = JSON.parse(this.#storage?.getItem(key) ?? ''); + if (!isObject(data)) return null; + const { value, expires } = data; // is this item has passed its sell-by-date, remove it - if (expires && new Date() > new Date(expires)) { + if (isString(expires) && new Date() > new Date(expires)) { this.remove(key); return null; } @@ -52,11 +47,6 @@ class StorageFactory { return null; } } - /* eslint-enable - @typescript-eslint/no-unsafe-assignment, - @typescript-eslint/no-explicit-any, - @typescript-eslint/no-unsafe-argument - */ /** * Save a value to storage.