TypeScript Variables & Type Annotations - Let, Const, Type Inference

Learn TypeScript variables! Type annotations, let, const, type inference, and basic types!

Introduction

Let's learn TypeScript variables and type annotations!

What You Will Learn

  • Type annotations
  • let and const in TypeScript
  • Type inference
  • Basic primitive types

Prerequisites

Type Annotations

TypeScript lets you explicitly state what type a variable should be!

// Syntax: variableName: Type = value;
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;

Type Inference!

TypeScript is smart! It can often infer the type automatically, so you don't have to write it every time!

let message = "Hello"; // TypeScript infers string!
let count = 42; // TypeScript infers number!
let isAdmin = false; // TypeScript infers boolean!

Only add type annotations when TypeScript can't infer!

Primitive Types!

Let's learn the basic types!

1. String!

let firstName: string = "John";
let lastName: string = 'Doe';
let fullName: string = `${firstName} ${lastName}`;

2. Number!

let age: number = 30;
let price: number = 99.99;
let negative: number = -10;

3. Boolean!

let isActive: boolean = true;
let isDisabled: boolean = false;

4. Null & Undefined!

let u: undefined = undefined;
let n: null = null;

let and const!

Just like modern JavaScript!

  • let: Reassignable!
  • const: Fixed value!
let count = 0;
count = 1; // Good!

const PI = 3.14;
// PI = 3; // Error!

Best Practices

  1. Prefer type inference: Don't add unnecessary annotations!
  2. Use const by default: Only let if you need to reassign!
  3. Avoid var: It's outdated!

Summary

Variables in TypeScript with type annotations and inference!

Related Articles

Previous Tutorial

Installing TypeScript

Next Tutorial

Let's dive into TypeScript types! → Basic Types