Distinguishing between types of Strings in TypeScript

Ari Picker
InstructorAri Picker
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:18] 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.

[00:44] 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.

[01:08] 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.

[01:33] 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.

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

DANIEL Pride
DANIEL Pride
~ 7 years ago

What are you using to write this? eclipse? storm?

Ari Picker
Ari Pickerinstructor
~ 7 years ago

Hey Daniel, I'm using Webstorm's Darcula theme.

Markdown supported.
Become a member to join the discussionEnroll Today