After previous question, occurs an error with new type CustomStorageFor
. How to fix the error inside initStorage()
? Typescript version 5.1.6
// Type 'string' cannot be used to index type 'CustomStorageFor<T>'
this.storage[key] = this.createStore(key, value)
type CustomStorageFor<T> = { [K in keyof T]: CustomStore<T[K]> } & {
[key: string]: CustomStore<T>
}
type CustomStore<T> = {
value: T,
init: (value: T) => void;
set: (value: T) => void;
}
class LiveStorage<T extends object> {
private defaultStorage: T
storage: CustomStorageFor<T>
constructor(defaultStorage: T) {
this.defaultStorage = defaultStorage
this.storage = {} as CustomStorageFor<T>
this.initStorage()
}
private async initStorage() {
Object.entries(this.defaultStorage).forEach(([key, value]) => {
// key: string, value: any
this.storage[key] = this.createStore(key, value)
})
}
private createStore<ValueType>(key: string, value: ValueType): CustomStore<ValueType> {
//...
}
}