字符串与字符串枚举不兼容

String is not compatible with String enum

我有这种类型:

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

然后我有这个 class:

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
}

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

如果您删除 StringtoUpper 并提供有效的默认值,一切都会起作用:

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