4

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.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

So in order to assign a value to one of these types I have to give it only one of the allowed string instead of how enums are used? Maybe I was confusing the two :)
0

I fell into a similar trap. What you can do is on your utils class create a static that returns a type of MyCustomType with the string text1.

public static readonly Text1:MyCustomType = 'text1';

Then you can do

let myVar:MyCustomType = UtilClass.Text1;

3 Comments

Thank you Dan! However this approach didn't work for me :(
@eagleEye sorry, had my C# hat on. Does my change to the static help?
Hi Dan, sorry didn't see your message until now, I hear you I mix languages all the time :D. I'll try and let you know.

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.