小编Zam*_*mmy的帖子

更新 ngx-translate 加载器中的翻译

我正在创建一个自定义 Angular ngx-translate Loader,它可以从缓存或 API 获取翻译。我遇到的问题是情况 2(参见下面的代码):

所需程序:

  1. 从缓存获取翻译(同步)
  2. 返回缓存的翻译(通过观察者)
  3. 从 api 获取翻译(异步)
  4. 比较缓存和api(发现差异)
  5. 发送更新版本的翻译 <-- 如何?

这就是我得到的:

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)

javascript ngx-translate angular

4
推荐指数
1
解决办法
3545
查看次数

当键缩小到对象的单个属性时,无法正确确定键/值对中值的类型

为什么当我缩小到 的单个可能属性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)

typeerror typescript

4
推荐指数
1
解决办法
348
查看次数