简体   繁体   中英

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 throws an error: TS2702: 'Example' only refers to a type, but is being used as a namespace here.

I know I can export the enum itself and use it in file2.ts , but I would like to know why the above example is not working.

Variant is a static class field

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

So if you want to use Variant as a type through class Example , you should add typeof before Example.Variant

 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 };

So the error came because you're using class as a namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM