[英]How to use enum (attached to a class as a static variable) as a type
// 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
中使用它,但我想知道為什么上面的示例不起作用。
變體是static
class 字段
export class Example { // Variant here is a class field static Variant = Variant; }
所以如果你想通過class
Example
使用 Variant 作為type
,你應該在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.