From the course: Learning TypeScript
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Allowing a variable to be multiple types - TypeScript Tutorial
From the course: Learning TypeScript
Allowing a variable to be multiple types
- [Instructor] In the last chapter, I showed you how to assign a single type to variable, along with how to use the any type to drop back to JavaScript's dynamic type, when you wanted to be able to use the same variable to represent multiple different types. When I showed you the any type, I also warned you to avoid it, because the more information you give Typescript, the better it can help you. In fact, let's go back to that example in which I showed you how to use the any type. In this example Typescript was complaining that I first assigned the original cost variable to a number, and then tried to reassign that same variable to a string value on the next line. Because I wanted the original cost variable to accept both string values and number values, at that point I used the any type to completely opt out of Typescript's type checking. But the ideal solution would be telling Typescript that the original cost…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.