【问题标题】:String is not compatible with String enum字符串与字符串枚举不兼容
【发布时间】:2018-05-01 01:50:45
【问题描述】:

我有这种类型:

export type BunionLevel = 'foo' | 'bar' | 'baz';

那么我有这个课程:

export class BunionLogger {

  level: BunionLevel;

  constructor(opts?: BunionOpts) {
    this.level = String((opts && (opts.level || opts.maxlevel) || maxLevel || '')).toUpperCase();
  }

}

我得到了这个编译错误:

呃,我该怎么办?我不知道该怎么做。我可以这样做:

this.level = <BunionLevels> String((opts && (opts.level || opts.maxlevel) || maxLevel || '')).toUpperCase();

但演员阵容似乎没有必要......?

根据要求,BunionOpts 看起来像:

export interface BunionOpts {
  level?: BunionLevel
  maxlevel?: BunionLevel
  appName?: string
  name?: string
  fields?: object
}

【问题讨论】:

  • BunionOpts 长什么样子?
  • 谢谢我刚刚添加了该信息
  • 有BunionLevel & BunionLevels吗?
  • 从您发布的代码看来,String 可能不是有效的BunionLevel 值;事实上,如果这真的是 exact 代码,它永远不会是。
  • 除了“BunionLevels”中的拼写错误外,它们看起来不兼容 - 例如,您的字符串有 null 和 '' 的大小写。它还有toUpperCase,而BunionLevel 没有一个大写字母。

标签: javascript node.js typescript typescript2.0


【解决方案1】:

如果您使用String 函数,则String((opts &amp;&amp; (opts.level || opts.maxlevel) || maxLevel || '')) 的结果将是string 而不是BunionLevel 的值。此外,由于您提供'' 作为默认值并且您使用toUpper,因此结果肯定不是BunionLevel 的有效字符串。

如果你删除 String 和 toUpper 并提供一个有效的默认值,一切都会奏效:

this.level = (opts && (opts.level || opts.maxlevel)) || 'foo';

【讨论】:

  • 没错。如果您希望默认值仍然是'',您可以将其添加到您的联合:type BunionLevel = 'foo' | 'bar' | 'baz' | '';
猜你喜欢
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多