Expert · TypeScript basics · topic 43 of 61 · 25 min
Basic types and inference
Explanation
Primitive types
let name: string = 'Asha';
let age: number = 29;
let isActive: boolean = true;
let big: bigint = 10n;
// In practice, let inference do this: let name = 'Asha';Arrays and tuples
const marks: number[] = [78, 92]; // or Array<number>
const names: string[] = [];
const point: [number, number] = [18.52, 73.85]; // a tuple: fixed length and types
const entry: [string, number] = ['rice', 40];
marks.push('ninety'); // Error: string is not assignable to numberFunctions
function addGst(amount: number, rate: number = 18): number {
return amount * (1 + rate / 100);
}
function greet(name: string, title?: string): string { // ? = optional
return title ? `${title} ${name}` : name;
}
function logVisit(page: string): void { // void: returns nothing useful
console.log('visited', page);
}
const double = (n: number): number => n * 2;Literal types and unions
A literal type is one exact value: 'GET' or 42. Combined with | (union, meaning "one of these"), they describe a fixed set of allowed values. This catches typos like 'POTS' at compile time.
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
function request(method: Method, url: string) { /* … */ }
request('POST', '/orders'); // OK
request('POTS', '/orders'); // Error: '"POTS"' is not assignable to type 'Method'.null and undefined
With strictNullChecks (part of strict), a string variable cannot hold null. If a value can be missing, say so in the type: string | null. Then TypeScript forces you to check before using it.
function findUser(id: number): { name: string } | undefined { /* … */ return undefined; }
const user = findUser(7);
console.log(user.name); // Error: 'user' is possibly 'undefined'.
console.log(user?.name); // OKany, unknown and never
| Type | Meaning | Use |
|---|---|---|
| any | Anything; checking turned off | Avoid; only when migrating old code |
| unknown | Anything, but you must check before use | Data from JSON.parse, APIs, user input |
| void | A function returns nothing useful | Return type of loggers, handlers |
| never | A value that can never exist | Functions that always throw; exhaustive checks |
const data: unknown = JSON.parse('{"amount": 5}');
data.amount; // Error: 'data' is of type 'unknown'.
if (typeof data === 'object' && data !== null && 'amount' in data) {
console.log((data as { amount: number }).amount); // allowed after checking
}Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Basic types and inference · 1/6
In this lesson you will use TypeScript's basic types.
Prefer a video by a teacher? Find free videos on “typescript basic types union literal unknown vs any” on YouTube ↗
In real life: Typing an API request helper
An internal tool at a bank calls dozens of endpoints. A typed helper accepts only the four allowed HTTP methods and a body that is an object, so a typo like "DELET" or passing a number as the body is caught in the editor.
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
function buildRequest(method: Method, url: string, body?: object) {
return { method, url, body: body ? JSON.stringify(body) : undefined };
}
buildRequest('POST', '/accounts', { name: 'Asha' });Practice (0/3 done)
Write average(marks: number[]): number that returns the average, or 0 for an empty array.
type Method = "GET" | "POST" | "PUT" | "DELETE". Write isMethod(value: string): boolean that returns true only for those four exact strings (this is the run-time check that matches the type).
Write describePoint(p: [number, number]): string that returns "lat <a>, lng <b>" with each number rounded to 2 decimals using toFixed(2).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Object types, interfaces and unionsTypeScript basics · same module
- GenericsTypeScript basics · same module
- Unions and narrowingFrontend Web Development · TypeScript basics
- Why TypeScriptFrontend Web Development · TypeScript basics
- Variables and primitive typesJava Programming (Core to Spring Boot) · Getting started with Java
- Strings are char arraysC Programming (from zero to systems) · Strings in C
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
How do you write "an array of strings"?
Answer: string[]
string[] (or Array<string>) is an array of strings. [string] is a tuple of exactly one.
Which type forces you to check a value before using it?
Answer: unknown
unknown accepts anything but blocks use until narrowed.
type Size = 'S' | 'M' | 'L'; const s: Size = 'XL'; What happens?
Answer: Compile error
'XL' is not one of the allowed literal types.
What does "x as number" do at run time?
Answer: Nothing; it only affects type checking
Assertions are erased; no conversion happens.
Why write const unreachable: never = p; in the default branch of a switch over a union?Related
Answer: It gives a compile error if a new member is added to the union but not handled
If every case is handled, p is never there. A missed case leaves a real type, which cannot be assigned to never.
From Unions and narrowing
Which of these is NOT a primitive type?Related
Answer: array
Arrays are objects. The primitives are string, number, bigint, boolean, undefined, null and symbol.
From Values and types
Why is unknown safer than any?Related
Answer: With unknown you must check the type before using the value; any turns checking off
any lets you do anything, even things that crash. unknown forces a check like typeof first.
From Why TypeScript
How many primitive types does Java have?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “TypeScript basics” before its exam: Object types, interfaces and unions, Generics, Utility types and real-world TypeScript.
- Module 9 exam: TypeScript basics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functional patterns and testing. 61 topics left in the course before the final exam.