簡體   English   中英

字符串與字符串枚舉不兼容

[英]String is not compatible with String enum

我有這種類型:

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
}

如果使用String函數,則String((opts && (opts.level || opts.maxlevel) || maxLevel || ''))將是一個string而不是BunionLevel的值。 另外,由於您默認提供''並使用toUpper ,因此結果絕對不是BunionLevel的有效字符串。

如果刪除StringtoUpper並提供有效的默認值,則將全部起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM