TypeScript BasicsBeginner7 min02 / 7

Basic Types

Learn how to label your variables with TypeScript's core types — string, number, boolean, and arrays — and discover how TypeScript can often figure out the type for you.

Imagine handing a note to a friend that says "Please bring me some _____". If you leave the blank empty, your friend might show up with anything — a pizza, a cactus, a confused look. But if you write "Please bring me some milk", there is no ambiguity. TypeScript works exactly the same way. Plain JavaScript lets you put anything into any variable, which is flexible but can lead to surprising bugs. TypeScript lets you label your variables so that both you and your editor always know exactly what kind of data to expect. In this lesson we will learn the most common labels: string, number, boolean, arrays, and the magic of type inference — where TypeScript reads your code and figures the label out on its own.

#The : Type Syntax

Adding a type annotation in TypeScript is simple: write a colon (:) after the variable name, then the type. That is the entire syntax. TypeScript reads the annotation and will warn you any time you try to store the wrong kind of value.

Annotating three common variable types
let username: string = "Alice";
let age: number = 30;
let isLoggedIn: boolean = true;

// TypeScript now prevents mistakes like this:
// age = "thirty"; // Error: Type 'string' is not assignable to type 'number'

#The Three Everyday Types

string holds text — anything wrapped in quotes. number holds integers and decimals alike (TypeScript, like JavaScript, does not separate them). boolean holds exactly one of two values: true or false. These three types cover the vast majority of data you will work with.

string, number, and boolean in action
let greeting: string = "Hello, world!";
let price: number = 9.99;
let isOnSale: boolean = false;

console.log(greeting);  // Hello, world!
console.log(price);     // 9.99
console.log(isOnSale);  // false

#Annotating Arrays

When all items in a list share the same type, you annotate it by writing the item type followed by []. So an array of numbers is number[], an array of strings is string[], and so on. TypeScript will flag it if you accidentally push the wrong kind of item into the array.

number[] and string[] array annotations
let scores: number[] = [98, 87, 76];
let colors: string[] = ["red", "green", "blue"];

scores.push(55);   // fine
// scores.push("A+"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'

console.log(scores);

#Type Inference — Let TypeScript Do the Work

Think of it like

TypeScript as a Smart Autocomplete

Think of type inference like your phone's autocomplete. You start typing "I love" and your phone already guesses the rest from context. TypeScript looks at the value you assign and infers the type automatically — you do not always have to spell it out.

When you initialize a variable with a value right away, TypeScript can infer its type without any annotation. The result is identical to annotating it explicitly — you get the same protection with less typing. This is idiomatic TypeScript: annotate when the type is not obvious, let inference handle the rest.

Inference in action — no annotation needed
// TypeScript infers all of these types automatically:
let city = "Tokyo";        // inferred: string
let temperature = 24.5;    // inferred: number
let isSunny = true;        // inferred: boolean
let ratings = [4, 5, 3];   // inferred: number[]

// Hover over a variable in your editor to see the inferred type!
// city = 42; // still an Error — inference gives full protection

#Avoid any — The Type That Opts You Out

Watch out

any turns off TypeScript's superpowers

The any type tells TypeScript "I do not care what this is" — and TypeScript believes you completely, checking nothing. It is like turning off spell-check. Reach for any only as a last resort; prefer specific types or TypeScript's other escape hatches (unknown) when you truly do not know the shape of data yet.

any disables all type checking — use sparingly
let mystery: any = "hello";
mystery = 42;        // no error
mystery = true;      // no error
mystery.foo.bar();   // no error at compile time — but will crash at runtime!

// Compare: a properly typed variable catches the mistake immediately:
let name: string = "Alice";
// name = 42; // Error caught before you even run the code
Quick check

What will TypeScript do if you write: let count = 10; count = "ten";

#Putting It All Together

Here is a small realistic snippet that uses everything from this lesson. Notice how annotations and inference work side by side — annotate what needs clarity, let TypeScript infer the rest.

Annotations on function parameters, inference on the return value
// Explicit annotations where the intent benefits from clarity:
function describeUser(name: string, age: number, isPremium: boolean): string {
  return `${name} is ${age} years old. Premium: ${isPremium}`;
}

// Inference handles the local variable:
const result = describeUser("Priya", 28, true);
console.log(result);

Key takeaways

  • Use the colon syntax (variableName: type) to annotate variables with string, number, boolean, or array types like number[].
  • TypeScript infers the type from the initial value, so you do not need annotations when the type is obvious from context.
  • Type annotations and inference both give the same protection — TypeScript will catch mismatches before your code runs.
  • Avoid any: it silences TypeScript's checks and reintroduces the very bugs you are trying to prevent.
  • Arrays are typed as ElementType[] — for example, string[] means every item must be a string.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

TypeScript types are erased before the code runs. What does this snippet print?

predict-output
let price: number = 9.99;
let isOnSale: boolean = false;
let colors: string[] = ["red", "green"];
colors.push("blue");

console.log(price);
console.log(isOnSale);
console.log(colors.length);
Fix the bug#2

This code has a bug — what's wrong?

fix-bug
let scores: number[] = [98, 87, 76];
scores.push("A+");
console.log(scores);
Fill in the blank#3

Complete the annotations using the colon type syntax. Fill each blank with the correct type for the value being assigned.

let username:  = "Alice";
let age:  = 30;
let isLoggedIn:  = true;
Reorder the lines#4

Arrange these lines so the code declares a product's details (letting TypeScript infer each type) and logs a sentence like 'Laptop costs $999. In stock: true'.

1
let price = 999;
2
let inStock = true;
3
let productName = "Laptop";
4
console.log(`${productName} costs $${price}. In stock: ${inStock}`);
Your turn
Practice exercise

Declare four variables: a string called productName, a number called price, a boolean called inStock, and a string[] called tags. Give each a sensible initial value. Then log a sentence that uses all four variables.

Try it live — edit the code and hit Run to see the output:

solution.ts · editable