total-typescript / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.74k stars 117 forks source link

Reset localStorage and sessionStorage #158

Closed kentcdodds closed 11 months ago

kentcdodds commented 11 months ago

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 🙃

kentcdodds commented 11 months ago

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

robbiespeed commented 11 months ago

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

mattpocock commented 11 months ago

@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.

mattpocock commented 11 months ago

Andarist is the GOAT:

https://twitter.com/AndaristRake/status/1689676010277457920

https://www.typescriptlang.org/play?target=9&module=7#code/KYDwDg9gTgLgBAbwL4G4BQaAmwDGAbAQymDgHM8IAjAvRNASAEsA7GYKAMwJxIGUZoBUiQQN6AbWYEAtsABccAM4woLUnABkiJAF0FAV2YBrZhADuzBkjTW0FHDX6DhAOkYvpBI8BfYAboouOFAAngAUAJQYAPTRcAAWMDBginKxpIww8fqUQRDS0QIwNAC0MCFgwIrBjGAwhYolxIrA9YyKivpV0QCMAKwAHGhAA

mattpocock commented 11 months ago

160

kentcdodds commented 11 months ago

Fantastic! Thank you!

kentcdodds commented 11 months ago

What's the release process for this library?