string, number, boolean
The three primitive types you will use most often.
Syntax
let 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.42or3.14.boolean—trueorfalse.
Use lowercase names (string, not String). The capitalized versions refer to wrapper objects and should be avoided.
Example
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.
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.
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.
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