Mastering TypeScript 3
上QQ阅读APP看书,第一时间看更新

Types, Variables, and Function Techniques

TypeScript introduces strong typing to JavaScript through a simple syntax, referred to by Anders Hejlsberg as syntactic sugar. This sugar is what assigns a type to a variable. This strong typing syntax, which is officially called type annotation, is used wherever a variable is used. In other words, we can use type annotation in a variable declaration, a function parameter, or to describe the return type of a function itself.

As we discussed in Chapter 1, TypeScript Tools and Framework Options, there are many benefits to enforcing types in a development language. These include better error checking, the ability for an IDE to provide more intelligent code suggestions, and the ability to introduce object-oriented techniques into the coding experience.

The TypeScript language uses several basic types, such as number and boolean, and also uses a few common rules to identify the type of a variable. Understanding these rules and applying them to your code is a fundamental skill when writing TypeScript code.

Along with these basic rules, the TypeScript compiler also adopts ES6 syntax to allow for more advanced object manipulation. This chapter introduces these basic types, the rules that the compiler uses for type checking, and then explores advanced object manipulation.

We will cover the following topics in this chapter:

  • Basic types and type syntax—strings, numbers, and booleans
  • Inferred typing and duck typing
  • Template strings
  • Arrays, and using for...in and for...of
  • The any type and explicit casting
  • Enums
  • The const and let keywords
  • Definite assignment and dotted property types
  • Functions and anonymous functions
  • Function parameters
  • Function callbacks, function signatures, and function overrides
  • Try catch
  • Advanced types, including union types, type guards, and type aliases
  • The never and unknown types
  • Object rest and spread
  • Tuples
  • Bigint
If you already have experience with TypeScript and have a good understanding of the language, then you can have a quick read through the entire chapter. Otherwise, you can skip on to the later parts of the chapter, where more advanced types, such as never, are explored.