Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a public enum in typescript?

For the following class:

module LayoutEngine {

    enum DocumentFormat {
        DOCX = 1
    };

    export class DocHeader {

        public format : DocumentFormat;
    }
}

I have two questions:

  1. The above has a compile error where it says "Public property 'format' of exported class has or is using private type 'DocumentFormat'." but a declaration of public before the enum is also an error. So how do I do this?
  2. Is there a way to place the enum declaration inside the class? Just a module name isn't great for namespacing as I have a lot of classes in that module.

thanks - dave

like image 651
David Thielen Avatar asked Apr 14 '14 23:04

David Thielen


People also ask

Can enums be public?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can I use enum as a type in TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

What Is A TypeScript enum?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


1 Answers

The above has a compile error where it says "Public property 'format' of exported class has or is using private type 'DocumentFormat'.

Simply export :

module LayoutEngine {

    export enum DocumentFormat {
        DOCX = 1
    };

    export class DocHeader {

        public format : DocumentFormat;
    }
}

Is there a way to place the enum declaration inside the class?

the enum typescript type needs to be at a module level (a file or inside a module). Of course if you want it inside the class just use a json object

module LayoutEngine {
    export class DocHeader {
        DocumentFormat = {
            DOCX: 1
        };

        public format : number;
    }
}
like image 123
basarat Avatar answered Sep 23 '22 23:09

basarat