Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
Is it possible to make a localStorage wrapper with TypeScript typed parameters and mapped return values?

I'm trying to construct a TS wrapper for localStorage with a TS schema that defines all the possible values in localStorage. Problem is that I can't figure out how to type the return value so that it's mapped to the approriate type from the schema: for example if I want to call LocalStorage.get("some_number"), I want the return type to be of type number. Is this even possible in TS?

Keys -typed parameter value works really well for the input!

type Values = LocalStorageSchema[Keys] returns the union type of the values which is not what I'm looking for.

Also it seems that it's not possible to use the variable key in the get function for type narrowing...

I have also looked into generic types: LocalStorage.get(...) but I think that kind of defeats the whole point of typing the return value.

Anyone got ideas for this? Thanks!

type LocalStorageSchema = {
  token: string;
  some_string: string;
  some_number: number;
};

type Keys = keyof LocalStorageSchema;
// type Values = LocalStorageSchema[Keys]; ???

export const LocalStorage = {
  get(key: Keys): any {
    const data = window.localStorage.getItem(key);

    //type ReturnType = ???
    if (data !== null) {
      return data;
    }

    console.error(`localStorage missing object with key ${key}`);
    return null;
  },

  set(key: Keys, value: any) {
    window.localStorage.setItem(key, value);
  },

  remove(key: Keys) {
    window.localStorage.removeItem(key);
  },

  clear() {
    window.localStorage.clear();
  },
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use generic as in this link. There are still some errors left to fix. Link how to handle null values. It's up to you, so I didn't fix it.

about 4 years ago · Juan Pablo Isaza Relatório

0

Use generics to return the right type for the key !

type LocalStorageSchema = {
    token: string;
    some_string: string;
    some_number: number;
};

type Keys = keyof LocalStorageSchema;

export const LocalStorage = {
    get<T extends Keys>(key: T): LocalStorageSchema[T] | null { // Return type will depend on the key
        const data = window.localStorage.getItem(key);

        //type ReturnType = ???
        if (data !== null) {
            return data as LocalStorageSchema[T];
        }

        console.error(`localStorage missing object with key ${key}`);
        return null;
    },

    set<T extends Keys>(key: T, value: LocalStorageSchema[T]) {
        window.localStorage.setItem(key, value as any);
    },

    remove(key: Keys) {
        window.localStorage.removeItem(key);
    },

    clear() {
        window.localStorage.clear();
    },
};

const a = LocalStorage.get('token'); // string | null

Playground

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda