JSDoc: Typedef из буквального

Для пользователей Postscript, желающих установить и получить типизированные свойства:

/**
 * Silly wrapper to be able to type the storage keys
 */
export class TypedStorage {

    public removeItem(key: keyof T): void {
        localStorage.removeItem(key);
    }

    public getItem(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);
    }

    public setItem(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);
    }
}

Пример использования :

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}
}

const storage: TypedStorage = new TypedStorage();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");

2
задан LazyOne 20 March 2019 в 13:24
поделиться