Chapter 2. Basic and custom types

 

This chapter covers

  • Declaring variables with types, and using types in function declarations
  • Declaring type aliases with the type keyword
  • Declaring custom types with classes and interfaces

You can think of TypeScript as JavaScript with types. That’s an oversimplified statement because TypeScript has some syntax elements that JavaScript doesn’t (such as interfaces, generics, and some others). Still, the main power of TypeScript is types.

Although declaring types of identifiers before their use is highly recommended, it’s still optional. In this chapter, you’ll start getting familiar with different ways of using the built-in and custom types. In particular, you’ll see how to use classes and interfaces to declare custom types; the coverage of classes and interfaces will continue in chapter 3.

Note

If you’re not familiar with the syntax of modern JavaScript, you may want to read the appendix before proceeding with learning TypeScript. This appendix will also help you understand which syntax elements exist in JavaScript and which were added in TypeScript.

2.1. Declaring variables with types

Why declare variable types if, in JavaScript, you can just declare a variable name and store the data of any type in it? Writing code in JavaScript is easier than in other languages mainly because you don’t have to specify types for identifiers, isn’t it?

2.2. Defining custom types

2.3. The any and unknown types, and user-defined type guards

2.4. A mini project

Summary

sitemap