Typescript

Typescript


How to Typescript

This fastest way to Typescript town, more paths are listed after

Static Typing

TypeScript adds static typing to JavaScript. You must declare types for variables, function parameters, and return values.

let x: number = 10;
let name: string = "Alice";
let isActive: boolean = true;

Type Inference

TypeScript can infer types automatically if you initialize a variable with a value.

let x = 10;  // TypeScript infers x as number
let name = "Alice";  // TypeScript infers name as string

Union Types

TypeScript allows variables to have multiple types using the | operator.

let value: number | string;
value = 10;  // Valid
value = "Hello";  // Also valid

Interfaces

Interfaces define the structure of objects. They are used for type-checking.

interface Person {
    name: string;
    age: number;
}

const person: Person = {
    name: "Alice",
    age: 25
};

Type Aliases

Type aliases allow you to create custom types. They are similar to interfaces but can represent any type.

type Point = {
    x: number;
    y: number;
};

const p: Point = { x: 10, y: 20 };

Generics

Generics allow you to create reusable components that work with multiple types.

function identity<T>(arg: T): T {
    return arg;
}

let output = identity<string>("Hello");  // Output is of type string

Enums

Enums allow you to define a set of named constants. They make code more readable.

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let dir: Direction = Direction.Up;

Optional and Default Parameters

Function parameters can be optional or have default values.

function greet(name: string, age?: number) {
    console.log(`Hello, ${name}`);
}

greet("Alice");  // age is optional

Type Assertions

Type assertions allow you to override TypeScript's inferred type.

let value: any = "Hello";
let length: number = (value as string).length;

Tuples

Tuples allow you to define an array with fixed types and lengths.

let tuple: [string, number];
tuple = ["Alice", 25];  // Valid
tuple = [10, "Alice"];  // Error

Readonly Properties

Properties marked as readonly cannot be modified after initialization.

interface Person {
    readonly name: string;
    age: number;
}

const person: Person = { name: "Alice", age: 25 };
person.name = "Bob";  // Error: Cannot assign to 'name'

Decorators

Decorators are a special kind of declaration that can be attached to classes, methods, or properties.

function log(target: any, key: string) {
    console.log(`${key} was called`);
}

class Person {
    @log
    greet() {
        console.log("Hello!");
    }
}

Namespaces

Namespaces are used to group related code and avoid naming collisions.

namespace MathUtils {
    export function add(a: number, b: number): number {
        return a + b;
    }
}

console.log(MathUtils.add(10, 20));  // 30

Type Guards

Type guards allow you to narrow down the type of a variable within a conditional block.

function isString(value: any): value is string {
    return typeof value === "string";
}

let value: string | number = "Hello";
if (isString(value)) {
    console.log(value.toUpperCase());  // Safe to call string methods
}

Utility Types

TypeScript provides built-in utility types like Partial, Pick, and Omit to manipulate types.

interface Person {
    name: string;
    age: number;
}

type PartialPerson = Partial<Person>;  // All properties are optional
type NameOnly = Pick<Person, "name">;  // Only the 'name' property

Strict Null Checks

TypeScript's strictNullChecks flag ensures that null and undefined are handled explicitly.

let x: number;
x = null;  // Error if strictNullChecks is enabled

Declaration Files

Declaration files (.d.ts) are used to describe the shape of existing JavaScript libraries.

// myLibrary.d.ts
declare module "myLibrary" {
    export function doSomething(): void;
}

TypeScript with React

TypeScript integrates seamlessly with React, providing type safety for props and state.

interface Props {
    name: string;
    age: number;
}

const Greet: React.FC<Props> = ({ name, age }) => (
    <div>Hello, {name}! You are {age} years old.</div>
);

Core Concepts

Type Annotations

// ๐Ÿท๏ธ Explicit type declarations
let age: number = 25;
let name: string = "Alice";
let isActive: boolean = true;

// ๐Ÿงฉ Array types
let numbers: number[] = [1, 2, 3];
let mixed: (string | number)[] = ["text", 42];

Interfaces

// ๐Ÿ“œ Object shape definition
interface User {
    id: number;
    name: string;
    email?: string;  // Optional property
}

// ๐Ÿ–จ๏ธ Usage
const user: User = { id: 1, name: "John" };

Enums

// ๐Ÿ”ข Named constants
enum Direction {
    Up = 'UP',
    Down = 'DOWN',
}

// ๐Ÿงญ Usage
const move: Direction = Direction.Up;

Type System

Union & Intersection

// ๐Ÿค Combine types
type ID = string | number;
type Admin = User & { privileges: string[] };

Type Guards

// ๐Ÿ” Runtime type checking
function isString(val: any): val is string {
    return typeof val === 'string';
}

// ๐Ÿ›ก๏ธ Safe type usage
if (isString(input)) {
    console.log(input.toUpperCase());
}

Advanced Types

Generics

// ๐Ÿงช Reusable type variables
function identity<T>(arg: T): T {
    return arg;
}

// ๐Ÿ“ฆ Generic interfaces
interface Box<T> {
    content: T;
}

Utility Types

// ๐Ÿ› ๏ธ Built-in type helpers
type PartialUser = Partial<User>;
type ReadonlyUser = Readonly<User>;
type StringKeys = keyof User;

Object-Oriented Programming

Classes

// ๐Ÿ—๏ธ Class with modifiers
class Animal {
    private name: string;
    protected age: number;
    
    constructor(name: string) {
        this.name = name;
    }
    
    public move(): void {
        console.log("Moving");
    }
}

Decorators

// ๐ŸŽ€ Metadata annotations
function log(target: any, key: string) {
    console.log(`Method ${key} called`);
}

class Calculator {
    @log
    add(a: number, b: number) { return a + b; }
}

Configuration

tsconfig.json

// โš™๏ธ Core compiler options
{
    "compilerOptions": {
        "target": "ES2020",
        "module": "CommonJS",
        "strict": true,
        "outDir": "./dist"
    }
}

Best Practices

Type Narrowing

// ๐Ÿ”ฆ Precise type control
function printId(id: string | number) {
    if (typeof id === 'string') {
        console.log(id.toUpperCase());
    } else {
        console.log(id.toFixed(2));
    }
}

Type Assertions

// โš ๏ธ Use with caution
const element = document.getElementById('root') as HTMLElement;
const value = <number>someUnknownValue;

Why Solo Dev?

This reference website is not for beginners
Solo Dev is strictly for devs who already know the game and need a beautiful cheat sheet on their second monitor which looks better than GeeksforGeeks


this portion goes away when you shrink the screen ;)

Our popular languages: