0

I have placed an enum in a seperate file so I can use that enum across files

Enums.ts

export enum Category {
    NotDefined,        
    BackData,
    Testing,
    Simulated
}

In another file i try to use my enum. I am trying to write a simple if/else or switch.

If i set the value of category == Category.Testing vscode is happy. If i try to set the value to something else e.g. "backData" as in the example below I get an error:

Type 'Category.Testing' is not comparable to type 'Category.BackData' 

Example code:

import { Category } from '@app/model/Enums.ts';

public async SubmitForm(): Promise<Boolean> {
    var category: Category;
    category = Category.BackData;

    switch (category) {
      case (Category.Testing): {
        ...
      }
      default: {
        ...
      }
    }

    if (category == Category.Testing) {
      ...
    } else {
      ...
    }
}

The error when setting the enum to another value that testing

enter image description here

2

2 Answers 2

1

As a workaround (for testing purposes only) you can write:

category = Category.BackData as Category;
Sign up to request clarification or add additional context in comments.

Comments

0

Typescript enums are nominal or opaque meaning that they are globally unique and unassignable to other or other types even if they're both the same.

export type IsEqual<A, B> = [A] extends [B] ? [B] extends [A] ? true : false : false

enum Foo {
    Foo
}

enum Bar {
    Bar
}

enum FooStr {
    Foo  = "hello"
}

enum BarStr {
    Bar = "hello"
}

type WhatType = IsEqual<Foo, Bar> // false.
type WhatType1 = IsEqual<Foo.Foo, Bar.Bar> // false even though both are 0
type WhatType2 = IsEqual<FooStr.Foo, BarStr.Bar> // false even though both are "hello"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.