TypeScript: Types

Typing is the key TypeScript feature.

So far we compiled a .ts file, but we just compiled plain JavaScript.

The most important piece of functionality provided by TypeScript is the type system.

If you ever used a typed language, like Go or C, you already know how this works. If not, and you only programmed in a dynamic language like Python or Ruby, this is all new to you but don’t worry.

The type system allows you, for example, to add types to your variables, function arguments and function return types, giving a more rigid structure to your programs.

The advantages are better tooling: the compiler (and editors like editors like VS Code) can help you a lot during development, pointing out bugs as you write the code. Bugs that couldn’t possibly be detected if you didn’t have types. Also, teamwork gets easier because the code is more explicit.

The resulting JavaScript code that we compile to does not have types, of course: they are lost during the compilation phase, but the compiler will point out any error it finds.

Here is how you define a string variable in TypeScript:

const greeting : string = "hello!"

Type inference lets us avoid writing the type in obvious cases like this:

const greeting = "hello!"

The type is determined by TS.

So basically our TypeScript can look like JavaScript. But each variable is now typed, and the editor (and the compiler) can help us write more correct code.

Lessons in this unit:

0: Introduction
1: Your first TypeScript program
2: ▶︎ Types
3: Typing functions
4: The editor helps you with type errors
5: Running TypeScript code
6: Valid types
7: Type aliases and interfaces
8: Union types
9: Typing arrays with generics
10: The DX of editing TypeScript
11: There's more...
Want to learn more? Check out our courses