And*_*ann 7 enums overloading typescript typescript-typings conditional-types
我正在将一些设置存储到本地存储中,并且我想在从/向存储获取(并且理想情况下还插入)值时输入响应。
据我所知,最好的方法似乎是使用函数重载。所以这就是我现在所拥有的并且它有效:
export enum SettingsKey {
hasOnboarded = 'hasOnboarded',
phoneNumber = 'phoneNumber'
}
export async function getSetting(storage: Storage, key: SettingsKey.phoneNumber): Promise<string>
export async function getSetting(storage: Storage, key: SettingsKey.hasOnboarded): Promise<boolean>
export async function getSetting(storage: Storage, key: any) {
return storage.get(key)
}
Run Code Online (Sandbox Code Playgroud)
我不喜欢这个解决方案的一点是,可能会忘记在枚举中添加一个新元素到重载类型定义中。有没有办法强制处理所有枚举值?或者有没有更好的方法来完全做到这一点?
我认为这将是一件简单的事情,从值hasOnboarded
到返回类型的映射boolean
等,但这显然不是那么容易。
在我看来,条件类型可能会解决这个问题,但我无法完全理解它是如何工作的。
我也看到了这种方法,但这似乎有点过多的开销。
任何见解将不胜感激!
Tit*_*mir 12
您可以使用额外的类型在枚举和承诺返回类型之间进行映射。然后我们添加一个泛型参数来getSettings
扩展SettingsKey
枚举并使用泛型类型来索引映射类型。泛型参数将根据我们指定为参数的枚举成员进行推断。
如果映射类型不包含枚举的所有键,我们将在函数上出错。
export enum SettingsKey {
hasOnboarded = 'hasOnboarded',
phoneNumber = 'phoneNumber'
}
type SettingsKeyReturnType = {
[SettingsKey.hasOnboarded]: boolean,
[SettingsKey.phoneNumber]: string
}
export async function getSetting<K extends SettingsKey>(storage: Storage, key: K): Promise<SettingsKeyReturnType[K]> {
return storage.get(key)
}
let a = getSetting(window.localStorage, SettingsKey.phoneNumber); // Promise<string>
let b = getSetting(window.localStorage, SettingsKey.hasOnboarded); // Promise<booelan>
// We can also define a set function in a similar way
export async function setSetting<K extends SettingsKey>(storage: Storage, key: K, value: SettingsKeyReturnType[K]): Promise<void> {
///...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2381 次 |
最近记录: |