简体   繁体   English

枚举的打字稿类型别名

[英]Typescript type alias for enum

I have this in my typings file:我的打字文件中有这个:

declare namespace Somatic {
    enum PropType {
        html,
        object,
        css
    }
}

In another file index.ts, I have a shorter alias for this enum as:在另一个文件 index.ts 中,我有一个较短的枚举别名:

type PropType = Somatic.PropType;

Then I want to use the aliased enum type in a switch statement:然后我想在 switch 语句中使用别名枚举类型:

switch (propType) {
    case PropType.html:
        break;
    .
    .
    .
    }

But Typescript does not recognize the aliased enum type values.但是 Typescript 无法识别别名枚举类型值。 What is wrong here?这里有什么问题?

You should use import keyword instead of type :您应该使用import关键字而不是type

import PropType = Somatic.PropType;

More info on import alias declarations here .有关导入别名声明的更多信息,请访问此处

** This syntax won't work if you're using babel-plugin-transform-typescript because this is typescript only form of import. ** 如果您使用babel-plugin-transform-typescript,则此语法将不起作用,因为这是 typescript 唯一的导入形式。 Generally using namespaces is not recommended.通常不推荐使用命名空间。

In typescript, an enum is both a type and a map.在打字稿中,枚举既是类型又是映射。 You should alias the type and the map separately:您应该分别为类型和地图设置别名:

type PropTypeEnum = Somatic.PropType;
const PropType = Somatic.PropType;

Basically, a definition file is simply declaring the type of existing other code.基本上,定义文件只是声明现有其他代码的类型。 Enums in TypeScript are actually numbers and more than likely the existing code you're building on top of doesn't use actual numbers. TypeScript 中的枚举实际上是数字,并且您在其上构建的现有代码很可能不使用实际数字。 A better implementation would probably be to just switch strings;更好的实现可能是只切换字符串;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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