Search code examples
typescripttypescript-genericstsc

How to create exported function aliases for type checking based on different arguments


I have this:

export const set = (k: LocalStorageKeys.CP_EMAIL, v: string) => void;
export const set = (k: LocalStorageKeys.CP_USER_ID, v: string) => void;
export const set = (k: LocalStorageKeys.CP_USER, v: User) => void;

export const set = (k: LocalStorageKeys, v: any) : void => {
  return localStorage.setItem(k, JSON.stringify(v));
};

but tsc doesn't like it, it says set is redeclared in the block:

TS2451: Cannot redeclare block-scoped variable 'set'.

is there a way to do what I am trying to do? My goal is to type-check the set function and if a key is a certain key, expect a certain type for the second argument.


Solution

  • On the TypeScript gitter channel, I got an answer:

    enter image description here

    Works very nicely, thanks!