total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's

Home Page:https://www.totaltypescript.com/ts-reset

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Reset localStorage and sessionStorage

kentcdodds opened this issue · comments

Right now these are typed like so:

interface Storage {
    readonly length: number;
    clear(): void;
    getItem(key: string): string | null;
    removeItem(key: string): void;
    setItem(key: string, value: string): void;
    [name: string]: any;
}

So doing this is totally cool:

sessionStorage.blah()
localStorage.i.make.devs.cry()

But there's no world where that would be ok.

I'm not sure whether this is possible. Me and ChatGPT couldn't figure out how to augment the built-in Session interface successfully 🙃

I made a TypeScript playground for folks who want to try their hand at this...

Hacky work around is to use template literals for the index signature, since overriding index signatures is not allowed.

For example this also doesn't work.

interface A {
  // TS Error: Duplicate index signature for type 'string'.(2374)
  [key: string]: any;
}
interface A {
  // TS Error: Duplicate index signature for type 'string'.(2374)
  [key: string]: unknown;
}

So I think the fact that it's an override of a global is just hiding the error, probably a TS bug.

This does work however:

type Character = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | '_' | '$';

interface A {
  [key: string]: any;
}
interface A {
  [key: `${Character | Uppercase<Character>}${string}`]: unknown;
}

TS playground

@robbiespeed This might actually be hacky enough to work. I just wish there was a way to cut down on that union type. Instantiating 52+ members is a bit expensive.

I'll ask the brain trust, see what comes back.

@kentcdodds I definitely agree that this is a great candidate for ts-reset, if possible.

Fantastic! Thank you!

What's the release process for this library?