Primitive types
Overview
Primitive types are the building blocks: text, numbers, true/false and the “empty” values. You already know them from JavaScript; this lesson is about how TypeScript treats them, and about the traps that types help you avoid.
string
const name: string = "Asha";
const greeting = `Hello, ${name}!`; // template literals are strings too
name.toUpperCase(); // the editor lists every string method
name.lenght;
// error TS2551: Property 'lenght' does not exist on type 'string'. Did you mean 'length'?TypeScript knows every method of every built-in type, which is half the value of using it: misspelled methods are caught immediately, and autocomplete shows you what’s available.
number
JavaScript has one number type for integers and decimals alike, and so does TypeScript:
const count: number = 42;
const price = 3.99;
const big = 1_000_000; // underscores for readability
const hex = 0xff; // 255Two special values are also numbers: NaN (“not a number”, the result of failed maths) and Infinity. TypeScript can’t tell them apart from normal numbers, so guard against them where they might appear:
const value = Number("12,50"); // NaN — the comma isn't valid
Number.isFinite(value); // false: rejects NaN and ±InfinityDecimal arithmetic is approximate (0.1 + 0.2 is 0.30000000000000004), exactly as in JavaScript. Types don’t change that — for money, work in whole cents or use a decimal library.
boolean
const isAdmin: boolean = false;
const canEdit = isAdmin || user.role === "editor"; // inferred booleanbigint
number can only represent whole numbers exactly up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). Beyond that, use bigint, written with an n suffix:
const id: bigint = 9007199254740993n;
const doubled = id * 2n;TypeScript stops you from mixing the two, because JavaScript would throw at run time:
id * 2;
// error TS2365: Operator '*' cannot be applied to types 'bigint' and 'number'.Convert explicitly with BigInt(2) or Number(id).
symbol
Symbols are unique values, mostly used as special object keys by libraries. You’ll rarely create your own:
const secret = Symbol("secret"); // unique symbolnull and undefined
undefinedmeans “not set yet”: missing properties, unassigned variables, functions that return nothing.nullmeans “deliberately empty”.
With strict mode on (the default), they are separate types: a string can’t be null. If something can be missing, you say so with a union: string | null. That rule alone prevents the most common JavaScript crash, “Cannot read properties of undefined”. null and undefined is all about it.
No implicit conversions
JavaScript converts types silently; TypeScript flags most of these conversions instead:
const total = "10" * 2;
// error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
const label = "Total: " + 20; // allowed: concatenating a number into text is common and safeWhen converting input, be explicit:
Number("42") // 42
Number("4 2") // NaN
parseInt("42px") // 42 — stops at the first non-digit
String(42) // "42"
(42).toFixed(2) // "42.00"Don’t use the wrapper types
JavaScript has object versions of primitives — String, Number, Boolean — and TypeScript has matching types. They are almost never what you want:
let a: String = "hi"; // works, but it's the wrong type
let b: string = "hi"; // ✓ always use the lower-case nameTwo types for “nothing”: void and the empty values
A function that doesn’t return anything has the return type void:
function log(message: string): void {
console.log(message);
}You’ll meet void, unknown and never properly in any, unknown and never.
Remember: lower-case names, no silent conversions,
bigintfor huge integers, andNumber.isFinitewhenever a number came from user input.
A typed toolbox
Write five small, fully annotated functions and call each one: (1) initials(fullName: string): string — "Ada King Lovelace" → "A.K.L."; (2) isAdult(age: number): boolean; (3) parsePrice(text: string): number that returns NaN-safe results — if Number(text) is not a finite number, return 0; (4) factorial(n: bigint): bigint — print factorial(25n), which is too big for a normal number; (5) formatBytes(bytes: number): string — 1536 → "1.5 KB", 5_000_000 → "4.8 MB", 512 → "512 B".
// 1. initials
// 2. isAdult
// 3. parsePrice
// 4. factorial with bigint
// 5. formatBytes// 1. initials
function initials(fullName: string): string {
return fullName
.split(" ")
.filter((part) => part.length > 0)
.map((part) => part[0]?.toUpperCase() + ".")
.join("");
}
// 2. isAdult
function isAdult(age: number): boolean {
return age >= 18;
}
// 3. parsePrice
function parsePrice(text: string): number {
const value = Number(text);
return Number.isFinite(value) ? value : 0;
}
// 4. factorial with bigint
function factorial(n: bigint): bigint {
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= i;
}
return result;
}
// 5. formatBytes
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
}
console.log(initials("Ada King Lovelace")); // A.K.L.
console.log(isAdult(17), isAdult(18)); // false true
console.log(parsePrice("12.50"), parsePrice("abc")); // 12.5 0
console.log(factorial(25n)); // 15511210043330985984000000n
console.log(formatBytes(512), formatBytes(1536), formatBytes(5_000_000));Summary
- The primitives are
string,number,boolean,bigint,symbol,nullandundefined— always written in lower case. numbercovers integers and decimals;NaNandInfinityare numbers too, so check withNumber.isFinite.bigint(written10n) handles whole numbers of any size, but can’t be mixed withnumberwithout converting.- TypeScript never converts between types for you:
"3" * 2and"a" + 1style code is flagged or must be explicit. - Avoid
String,NumberandBoolean(capitalised) as types — they are object wrappers.