Basic types: primitives, arrays, tuples, any and unknown
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Type annotations and inference
You add a type after a name with a colon. This is a type annotation.
const userName: string = "Sara";
const age: number = 28;
const isActive: boolean = true;
let score: number = 10;
score = 20;
// score = "high"; // Error: Type 'string' is not assignable to type 'number'
console.log(userName, age, isActive, score);
You often do not have to write the type, because TypeScript works it out from the value. This is type inference:
const city = "Lahore"; // type is "Lahore" (a literal, because it is const)
let count = 0; // type is number
let flag = true; // type is boolean
count = count + 1; // fine
// flag = "yes"; // Error
My rule is to let inference do the work for local variables, and to write the types explicitly on function parameters and on the shape of data that crosses boundaries (API results, function returns that are exported). That gives you most of the safety with the least noise.
The primitive types
| Type | Example values |
|---|---|
string | "hello", 'hi', template |
number | 42, 3.14, NaN. Whole numbers and decimals are both number |
boolean | true, false |
bigint | 123n |
symbol | Symbol("id") |
null and undefined | The empty values. They have their own types |
Use the lower case names. Types such as String and Number with a capital letter refer to wrapper objects and you almost never want them.
Arrays
Two equivalent ways to write an array type:
const scores: number[] = [90, 85, 70];
const names: Array<string> = ["Ali", "Sara"];
scores.push(100);
// scores.push("a"); // Error
const first = scores[0]; // number
console.log(first, names);
I use number[] for simple cases and Array<...> when the element type is long. An empty array needs an annotation or TypeScript infers a poor type:
const items: string[] = [];
items.push("one");
console.log(items);
Tuples
A tuple is an array with a fixed length where each position has its own type:
const point: [number, number] = [10, 20];
const entry: [string, number] = ["age", 28];
const [key, value] = entry;
console.log(key.toUpperCase(), value + 1, point[0]);
// const bad: [string, number] = [28, "age"]; // Error
Tuples are useful for returning two or three related values from a function, much like destructured pairs in JavaScript. You can also name the positions for readability: type Range = [start: number, end: number].
any: the escape hatch
The any type switches off checking. A value of type any can be used as anything, and TypeScript will not complain:
let data: any = "hello";
data = 42;
data = { a: 1 };
console.log(data.something.deep); // compiles; at runtime, undefined
That last line compiles, and crashes only when data.something is undefined and you read .deep. With any, you are back to plain JavaScript, and any spreads: a value derived from an any is also any. Use it only as a last resort, for instance for a quick prototype or while migrating old code.
unknown: the safe version
When you truly do not know what a value is, use unknown. You can put anything into it, but you must check the type before using it.
function describe(value: unknown): string {
if (typeof value === "string") {
return `text of length ${value.length}`;
}
if (typeof value === "number") {
return `number ${value.toFixed(1)}`;
}
if (Array.isArray(value)) {
return `array with ${value.length} items`;
}
return "something else";
}
console.log(describe("hello")); // text of length 5
console.log(describe(3.14159)); // number 3.1
console.log(describe([1, 2])); // array with 2 items
console.log(describe(null)); // something else
Inside each if, TypeScript knows the narrower type. This is called narrowing, and it is the topic of a later lesson. The point is that unknown forces you to prove what the value is before you use it. For anything that comes from outside your program, such as JSON.parse, user input or a network response, unknown is the honest type.
void, never and object
voidis the return type of a function that returns nothing.neveris the type of something that cannot happen, for example a function that always throws.objectmeans any non-primitive value. In practice, you describe the shape instead.
function log(message: string): void {
console.log(message);
}
function fail(message: string): never {
throw new Error(message);
}
log("done");
Type assertions
Sometimes you know more than the compiler. An assertion with as tells it to trust you:
const input = { value: "42" } as { value: string };
const el = document.querySelector("#price") as HTMLInputElement | null;
console.log(input.value, el?.value);
An assertion does not change the value or check anything at runtime. If you are wrong, you get a crash later. Prefer narrowing with a real check, and use as sparingly.
Common mistakes
- **Using
anyto silence an error.** Tryunknownand a check instead. - Capital letter types. Write
string, notString. - Declaring an empty array without a type. In strict mode
const a = []starts as an evolving type that can surprise you. Annotate:const a: string[] = []. - Over-annotating.
const x: number = 5adds nothing. - **Trusting
as.** It is a promise to the compiler, and the compiler cannot verify it. - **Mixing up
nullandundefined.** They are separate types, and strict mode makes you handle both.
Try it yourself
- Declare variables of each primitive type and try to assign the wrong type to one of them.
- Create a tuple type for
[string, number, boolean]and destructure it. - Write a function
safeLength(value: unknown): numberthat returns the length for strings and arrays and 0 for anything else. - Replace an
anyin one of your old snippets withunknownand fix the errors that appear.
const userName: string = "Sara";
const age: number = 28;
const isActive: boolean = true;
let score: number = 10;
score = 20;
// score = "high"; // Error: Type 'string' is not assignable to type 'number'
console.log(userName, age, isActive, score);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account