【问题标题】:How to use enum (attached to a class as a static variable) as a type如何使用枚举(作为静态变量附加到类)作为类型
【发布时间】:2020-08-10 14:06:01
【问题描述】:

// file1.ts

enum Variant {
  Success = 'success',
  Error = 'error',
}

export class Example {
  static Variant = Variant;
}


// file2.ts

import { Example } from './file1';

type Props = {
  variant: Example.Variant; // TS2702: 'Example' only refers to a type, but is being used as a namespace here.
};

Typescript 抛出错误:TS2702: 'Example' only refers to a type, but is being used as a namespace here.

我知道我可以导出枚举本身并在file2.ts 中使用它,但我想知道为什么上面的示例不起作用。

【问题讨论】:

    标签: javascript reactjs typescript enums


    【解决方案1】:

    Variant 是 static 类字段

    export class Example {
      // Variant here is a class field
      static Variant = Variant;
    }

    因此,如果您想将 Variant 用作typeclass Example,则应在Example.Variant 之前添加typeof

    import { Example } from './file1';
    
    type Props = {
      // This statement means that Example is a namespace that contains Variant as a type or class named Variant, which in our case it is a field
      variant: Example.Variant; // wrong
      variant: typeof Example.Variant; // correct
    };

    所以出现错误是因为您使用class 作为namespace

    【讨论】:

    • 知道了。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2022-01-15
    • 1970-01-01
    • 2011-04-27
    • 2018-04-08
    相关资源
    最近更新 更多