string, number, boolean

The three primitive types you will use most often.

Syntaxlet n: number = 10; let s: string = "hi"; let b: boolean = false;

TypeScript has three core primitive types that mirror JavaScript's:

  • string — text, e.g. "hello".
  • number — integers and decimals, e.g. 42 or 3.14.
  • booleantrue or false.

Use lowercase names (string, not String). The capitalized versions refer to wrapper objects and should be avoided.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A form validation function accepts a string name and number age, rejecting mismatched inputs at compile time.
  • A shopping cart calculates a total price using number arithmetic, preventing accidental string concatenation bugs.
  • A feature-flag system stores toggle states as boolean values, making conditional logic easy to type-check.

More examples

Declare the three primitives

Declares one variable of each primitive type with an explicit annotation, the foundation of TypeScript typing.

Example · ts
const firstName: string = 'Alice';
const age: number = 28;
const isAdmin: boolean = false;

console.log(`${firstName}, age ${age}, admin: ${isAdmin}`);

Primitives in a function

Uses all three primitive types as function parameters with a typed string return, showing real-world combined usage.

Example · ts
function formatUser(name: string, age: number, active: boolean): string {
  const status = active ? 'active' : 'inactive';
  return `${name} (${age}) — ${status}`;
}

formatUser('Bob', 32, true);

Type mismatch errors

Shows compile-time errors when assigning incompatible values, illustrating how strict primitive typing prevents common mistakes.

Example · ts
let price: number = 9.99;
price = '9.99';   // Error: Type 'string' is not assignable to type 'number'

let flag: boolean = true;
flag = 1;         // Error: Type 'number' is not assignable to type 'boolean'

Discussion

  • Be the first to comment on this lesson.