2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】localSrorageに型定義する

Last updated at Posted at 2024-04-01

自分用メモ

やること

変更前 変更後
image.png image.png

anyであるところに型を付けます。

方法

type StorageKey = 'count';

declare global {
  interface Storage {
    count?: string;
    getItem(key: StorageKey): string | null;
    setItem(key: StorageKey, value: string): void;
    removeItem(key: StorageKey): void;
  }
}

const count = localStorage.count; // string | undefined

getItemsetItemも入力補完が付いていいね👍
image.png

注意

既存の型定義を上書きではなく、追記の形になるのでlocalStorage.itemといったものはanyとみなされて、型エラーになりません。
既存定義の上書きはできないみたいですので、マジの型安全のlocalStorageを使いたい場合は下記みたいに新しく使いたいlocalStorageを作ってESLintでlocalStorage使用を制限するカスタムルールを作ると良さそう

type StorageKey = 'count';
const customLocalStorage = {
  ...localStorage,
  count: localStorage.count as string | undefined,
  getItem: (key: StorageKey) => localStorage.getItem(key),
  setItem: (key: StorageKey, value: string) => localStorage.setItem(key, value),
  removeItem: (key: StorageKey) => localStorage.removeItem(key),
};
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?