Chapter 2. Basic Types

Now that you are all set up, it’s time to write some TypeScript! Starting out should be easy, but you will soon run into situations where you’re unsure if you’re doing the right thing. Should you use interfaces or type aliases? Should you annotate or let type inference do its magic? What about any and unknown: are they safe to use? Some people on the internet said you should never use them, so why are they part of TypeScript?

All these questions will be answered in this chapter. We will look at the basic types that make TypeScript and learn how an experienced TypeScript developer will use them. You can use this as a foundation for the upcoming chapters, so you get a feel for how the TypeScript compiler gets to its types and how it interprets your annotations.

This is about the interaction between your code, the editor, and the compiler. And it’s about going up and down the type hierarchy, as we will see in Recipe 2.3. Whether you’re an experienced TypeScript developer or just starting out, you’ll find useful information in this chapter.

2.1 Annotating Effectively

Problem

Annotating types is cumbersome and boring.

Solution

Annotate only when you want your types checked.

Discussion

A type annotation is a way to explicitly tell which types to expect. You know, the prominent stuff in other programming languages, where the verbosity of StringBuilder stringBuilder = new StringBuilder() makes sure that you’re really, really dealing with a StringBuilder. The ...

Get TypeScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.