TypeScript Basics

A quick notes for beginners

·

2 min read

TypeScript Basics

Types:

The primitives: string, number, and boolean

  • string represents string values like "Hello, world"

  • number is for numbers like 45. JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number

  • boolean is for the two values true and false

any

TypeScript also has a special type, any, that you can use whenever you don’t want a particular value to cause typechecking errors.

Object Types

The most common sort of type you’ll encounter is an object type. This refers to any JavaScript value with properties, which is almost all of them! To define an object type, we simply list its properties and their types.

Union Types

The first way to combine types you might see is a union type. A union type is a type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union’s members.

Literal Types

In addition to the general types string and number, we can refer to specific strings and numbers in type positions. One way to think about this is to consider how JavaScript comes with different ways to declare a variable. Both var and let allow for changing what is held inside the variable, and const does not. This is reflected in how TypeScript creates types for literals.

Enums

Enums are a feature added to JavaScript by TypeScript which allows for describing a value which could be one of a set of possible named constants. Unlike most TypeScript features, this is not a type-level addition to JavaScript but something added to the language and runtime. Because of this, it’s a feature which you should know exists, but maybe hold off on using unless you are sure.

Did you find this article valuable?

Support Dhanush.K by becoming a sponsor. Any amount is appreciated!