eagleEye eagleEye - 1 month ago 11
TypeScript Question

Referencing a TypeScript type in Angular 2

this might be a basic question but maybe my knowledge of c# is misleading me. I'm currently trying to reference a custom type in Typescript and it only allows it when I actually provide the string value instead of the type reference. This is what I have:

export type MyCustomeType=
'text1' |
'text2' |
'text3';

export class MyCustomeTypeUtils {}


In my component I have declared variables of my custom type:

var1 : MyCustomeType;


The only way I get var1 to have a value is if I do:

var1 = 'text1'


If I do

var1 = MyCustomeType.0


or

var1 = MyCustomeType.text1


it throws an error that it couldn't find the name MyCustomeType. Any help is greatly appreciated.

Answer

That's how it works. This is what TypeScript calls String Literal Types

String literal types allow you to specify the exact value a string must have. In practice string literal types combine nicely with union types, type guards, and type aliases. You can use these features together to get enum-like behavior with strings.

type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
    animate(dx: number, dy: number, easing: Easing) {
        if (easing === "ease-in") {
            // ...
        }
        else if (easing === "ease-out") {
        }
        else if (easing === "ease-in-out") {
        }
        else {
            // error! should not pass null or undefined.
        }
    }
}

let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy"); // error: "uneasy" is not allowed here

You can pass any of the three allowed strings, but any other string will give the error

Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'

Note: If you want to use real enums TypeScript supports that

Comments