【问题标题】:Type 'string' is not assignable to type enum error类型“字符串”不可分配给类型枚举错误
【发布时间】:2020-05-04 14:35:08
【问题描述】:

我有一个界面如下:

export interface Preferences {
  theme: Theme;
}

Theme 被定义为枚举:

export enum Theme {
  dark = 'dark',
  light = 'light'
}

假设我有一个 JSON 文件如下:

{
  "theme": "light"
}

还假设我想在服务中使用它,如下所示:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Preferences } from '../models/preferences';
import prefExample from '../../assets/preferences.json';

@Injectable({
  providedIn: 'root'
})
export class MyService {

  constructor(private httpClient: HttpClient) { }

  getPreferences(): Observable<Preferences> {
    return of(prefExample);
  }
}

当我尝试运行上面的代码时,它告诉我:

Types of property 'theme' are incompatible.
  Type 'string' is not assignable to type 'Theme'.

【问题讨论】:

  • prefExample as Preferences?或者写一些接受 JSON 并返回 Preferences 的东西。

标签: json angular enums rxjs observable


【解决方案1】:

如果您确定 Preferences 的 JSON 数据有效,您可以告诉 TypeScript 编译器使用 prefExample 对象作为 Preferences,如下所示:

getPreferences(): Observable<Preferences> {
    return of(prefExample as Preferences);
}

【讨论】:

  • TS2352:类型转换'{主题:字符串; }' 来输入 'Preferences' 可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请先将表达式转换为“未知”。看来我应该将其转换为unknown,然后再转换为Preferences。为什么这是必要的?
  • 你使用什么版本的打字稿?我使用~3.8.3 检查了代码,它的编译没有任何错误。我也使用了这样的导入import * as prefExample from '../../assets/preferences.json',因为没有export,您无法导入默认值
猜你喜欢
  • 2021-10-01
  • 2019-02-27
  • 2021-09-29
  • 2019-06-15
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
相关资源
最近更新 更多