我对TypeScript和相关技术非常陌生。*眨眼:
我使用Nest.js和cache-manager。在cache-manager中,我可以使用await this.cacheManager.get<type>(key)获得一个键值。type需要替换为真正的类型(很明显)。
当cache-manager将所有值保存为字符串时,我希望强制执行该值的类型。我在cache-manager中在key/type值下创建另一条记录。由于这是一个字符串,我如何在this.cacheManager.get<type>()中将它作为数据类型传递
更新
下面是一个更直观的示例,说明我想使用switch()…做什么应该有一种更简洁的方法来使用某种动态类型(或者不管它被称为什么)来完成它。
async getValue(name: string, type?: string): Promise<boolean | number | object | string> {
type ||= await this.cacheManager.get<string>(`${name}/type`) || 'string'
switch (type) {
case 'boolean':
return await this.cacheManager.get<boolean>(name)
case 'number':
return await this.cacheManager.get<number>(name)
case 'object':
return JSON.parse(await this.cacheManager.get<string>(name))
default:
return await this.cacheManager.get<string>(name)
}
}发布于 2021-12-11 17:48:41
也许试着用泛型?就像这样:
async getCacheValue<T>(name: string): Promise<T> {
return await this.cacheManager.get<T>(name)
}然后按如下方式调用该方法:
getCacheValue<type>(name)我一点也不熟悉Nest.JS或缓存管理器,很抱歉我还没有理解,但这可能会为您指明正确的方向。
https://stackoverflow.com/questions/70314685
复制相似问题