Cristiano Casciotti
Cristiano Casciotti

Reputation: 1026

Correct type definition for a variable assigned with an enum

I'm wondering what is the correct type definition for a variable assigned with an enum inside an Angular's component.

Consider this situation:

@Component({
    selector: 'dashboard-component',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent {
    componentActions = ComponentActions;

    ...
}

export enum ComponentActions {
    ACTION_OK,
    ACTION_CANCEL,
}

Basically, I need to use ComponentActions enum inside my component's template, so I assigned the componentActions public variable with the ComponentActions enum, and I want to specify the type of this public variable.

The following code:

componentActions: ComponentActions = ComponentActions;

will throws an error in tslint:

Type 'typeof ComponentActions' is not assignable to type 'ComponentActions'

Otherwise, using the following code:

componentActions: typeof ComponentActions = ComponentActions;

there is no error from tslint.

My question is: what is the correct type for the public variable? It's sufficient to use typeof keyword or there is a specific way?

Thanks in advance.

Upvotes: 1

Views: 95

Answers (3)

Cristiano Casciotti
Cristiano Casciotti

Reputation: 1026

So I'm going to answer my own question.

Accordingly to typescript's definition, in the below code:

componentActions: typeof ComponentActions = ComponentActions;

the typeof is called type query.

A type query obtains the type of an identifier or property access expression and it's the most close to achieve my goal.

Upvotes: 2

Ronald Korze
Ronald Korze

Reputation: 828

Type 'typeof ComponentActions' is not assignable to type 'ComponentActions'

The error states that you tried to assign a type to a variable of a type - of course this is not possible. To assign a value to the enum variable:

componentActiosn: ComponentActions = ComponantActions.ONE_OF_YOUR_DEFINED_ENUM VALUES; (ACTION_OK, ACTION_CANCEL)

Upvotes: 0

Denerator
Denerator

Reputation: 451

You should not assign enum to the variable. Enum is just an object. You need to pass the type and assign one of the enums values.

componentActions: ComponentActions = ComponentActions.ACTION_OK;

Upvotes: 1

Related Questions