我正在创建一个自定义 Angular ngx-translate Loader,它可以从缓存或 API 获取翻译。我遇到的问题是情况 2(参见下面的代码):
所需程序:
这就是我得到的:
getTranslation(lang: string): Observable<any> {
return new Observable(observer => {
// get translations from cache + start getting translations from API
const cachedTranslations = this.cacheService.getTranslation(lang);
const apiTranslations = this.http.get(environment.translationApi + lang);
if (cachedTranslations) {
// CASE #1: return cached translations
observer.next(cachedTranslations);
}
apiTranslations.subscribe(translations => {
// CASE #2: if cached translations are not up to date
// or dont exist, add new translations …Run Code Online (Sandbox Code Playgroud) 为什么当我缩小到 的单个可能属性value时,无法正确确定 的类型- 即使 的类型是 中该属性的类型?keyobjvalueobj
const obj = {
a: "FOO",
b: 123,
}
const doSomething = <T extends keyof typeof obj>(key: T, value: typeof obj[T]) => {
if (key === 'a') {
value.toUpperCase();
// Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
}
}
Run Code Online (Sandbox Code Playgroud)
我假设这甚至可能是尚未在打字稿中实现的东西,但我找不到有关此问题的任何信息。
编辑(进一步澄清目标):
我并不是想使用中的属性值obj。我想设置一个满足 中属性类型的新值obj。对于某些特定的键,我想预先转换值。像这样的东西:
const setValue = <T extends keyof typeof …Run Code Online (Sandbox Code Playgroud)