Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Distinguishing between types of Strings in TypeScript


    In JavaScript, many libraries use string arguments to change behavior. In this lesson we learn how Typescript catches string related errors at compile time by assigning a string literal as a type.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Annotating a variable as a string type looks like this. Annotating a variable as a string literal type looks like this. The stringType variable can be set to any string, but the stringLiteralType can only be set to the type value, as well as Null and Undefined, as of now.

    When we set the stringLiteralType to a value that is incorrect, the IDE will alert us, as well as the compiler. Type "awesome" is not assignable to type "S". This stringLiteralType by itself isn't that useful, but when combined with union types and alias types, they help document your code, catch errors, and large concepts can be boiled down to one alias.

    To demonstrate, I'm going to make a function that accepts a number and a string. When I call the function, I can pass any number and any string. When we run the compiler, no errors. When we run the code, that's what I was going for. However, I can also pass the wrong string value. Run the compiler, no errors because I said any string. When we run the code, this is not what I was going for.

    Instead, lets make a type alias using string literals and union types. Now let's update our value argument to be a distance metric. Already the IDE is alerting us that "dragon" is incorrect. If we run the compiler, it will say the same thing. "Dragon" is an unacceptable value for a type that can only be these values.

    To review, stringLiteralType values can only be set to its type, as well as Null and Undefined, for now. They're great for documenting your code, catching typos, and prevent assigning the wrong string. When combined with union types and alias types, string literals boil down large concepts to one alias.

    For example, if our value requirement can only be specific string parameters, string literal types, union types, and alias types make that really easy.