Appearance
Advanced Types
Now that you understand the basic types, let's explore more complex type structures including arrays, objects, and functions.
Array Types
There are two ways to annotate array types in TypeScript:
ts
let arr1: number[] = [1, 2, 3];
let arr2: Array<number> = [1, 2, 3];Both are equivalent, but using typename[] is more common. Some more examples:
ts
let stringArray: string[] = ["hello", "world"];
let booleanArray: boolean[] = [true, false, true];TypeScript will infer array types too:
ts
let arr1 = [1, 2, 3]; // inferred as number[]
let stringArray = ["hello", "world"]; // inferred as string[]
let booleanArray = [true, false, true]; // inferred as boolean[]Object Types
You can define object shapes inline with specific property types:
ts
let obj: { a: number; b: string } = { a: 1, b: "hello" };TypeScript will infer object types too:
ts
let obj = { a: 1, b: "hello" }; // inferred as { a: number; b: string }Function Types
Functions can have typed parameters and return values:
ts
function add(a: number, b: number): number {
return a + b;
}
// Arrow function syntax:
const multiply = (a: number, b: number): number => a * b;
// Function with no return value:
function logMessage(message: string): void {
console.log(message);
}Optional Values
The ? operator indicates an optional value. This is used to define optional parameters for functions:
ts
// Function with optional parameters:
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
} else {
return `Hello, ${name}!`;
}
}
// Usage:
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Good morning"); // "Good morning, Bob!"Objects can also have optional properties using the ? operator:
ts
type User = {
name: string;
email: string;
age?: number; // Optional property
};
const user1: User = { name: "Alice", email: "alice@example.com" }; // OK
const user2: User = { name: "Bob", email: "bob@example.com", age: 25 }; // OK
// TypeScript knows age might be undefined:
if (user1.age) {
console.log(`${user1.name} is ${user1.age} years old`);
}Function Types as Parameters
Sometimes you need to pass functions as parameters, for example to define callback functions. TypeScript allows you to specify function types:
ts
// Simple function that takes a callback:
function doSomething(callback: () => void): void {
console.log("Starting...");
callback();
console.log("Finished!");
}
// Usage:
doSomething(() => console.log("Hello from callback!"));🤔 Adding function types to function parameters can make your code hard to read. In a moment, you'll see how TypeScript type aliases can be used to avoid that.
External Resources