TypeScript Constructs
Contents
About
Here are some TypeScript constructs that are useful to memorize:
TypeScript Constructs
Basic Types and Interfaces
TypeScript adds static types to JavaScript. Here are some examples:
let isDone: boolean = false;
let age: number = 30;
let firstName: string = "Andrew";
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42];
// Interfaces define shapes of objects
interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
}
const alice: Person = { name: "Alice", age: 25 };
Functions and Parameters
TypeScript allows parameter types, return types, and default values:
function greet(name: string = "World"): string {
return `Hello, ${name}!`;
}
const square = (num: number): number => num * num;
console.log(greet()); // Hello, World!
console.log(square(4)); // 16
TypeScript also supports function overloads:
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x: any, y: any): any {
return x + y;
}
console.log(add(1, 2)); // 3
console.log(add("a", "b")); // "ab"
Classes and Inheritance
TypeScript supports object-oriented programming with classes:
class Animal {
constructor(public name: string) {}
move(): void {
console.log(`${this.name} is moving.`);
}
}
class Dog extends Animal {
bark(): void {
console.log(`${this.name} says: Woof!`);
}
}
const myDog = new Dog("Buddy");
myDog.move(); // Buddy is moving.
myDog.bark(); // Buddy says: Woof!
Generics
Generics provide flexibility with types:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello");
console.log(output); // Hello
Generics also work with interfaces and classes:
interface Box<T> {
contents: T;
}
let stringBox: Box<string> = { contents: "Hello, World!" };
React-like Examples
TypeScript pairs well with React to build strongly typed UI components:
// Functional Component
import React from "react";
interface ButtonProps {
label: string;
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
// Usage
<Button label="Click me" onClick={() => alert("Clicked!")} />
State and hooks with TypeScript:
import React, { useState } from "react";
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Type Assertions
TypeScript allows asserting types explicitly:
let value: any = "this is a string";
// Type assertions
let length: number = (value as string).length;
// Alternative syntax
let lengthAlt: number = (<string>value).length;
Enums
Enums define a set of named constants:
enum Direction {
UP,
DOWN,
LEFT,
RIGHT,
}
console.log(Direction.UP); // 0
console.log(Direction[0]); // "Up"
Constants
Constants in TypeScript are defined using the `const` keyword and are generally written in **UPPER_CASE** if they represent constant values that don't change. You can also group constants into objects or use `const enum` for optimized performance.
const PI = 3.14159;
const MAX_USERS = 100;
const APP_NAME = "MyApp";
console.log(`App: ${APP_NAME}, Max Users: ${MAX_USERS}`);
For related constants, you can group them into objects for better organization:
const API_ENDPOINTS = {
USERS: "/api/users",
POSTS: "/api/posts",
COMMENTS: "/api/comments",
};
console.log(API_ENDPOINTS.USERS); // "/api/users"
Utility Types
TypeScript includes built-in utility types for common patterns:
interface Person {
name: string;
age: number;
address?: string;
}
// Partial makes all properties optional
const partialPerson: Partial<Person> = { name: "Alice" };
// Readonly makes all properties immutable
const readonlyPerson: Readonly<Person> = { name: "Alice", age: 30 };
// Pick selects specific properties
const pickedPerson: Pick<Person, "name"> = { name: "Alice" };
// Record creates a map-like structure
const phoneBook: Record<string, string> = {
"John": "123-456-7890",
"Alice": "987-654-3210",
};
Modules and Imports
TypeScript uses ES Modules for importing/exporting:
// Export
export const add = (a: number, b: number): number => a + b;
// Import
import { add } from "./math";
console.log(add(2, 3)); // 5