DEV Community

Cover image for Typescript Core Concepts
MD Moshiur Rahman
MD Moshiur Rahman

Posted on

Typescript Core Concepts

Introduction to TypeScript: Core Concepts Every Developer Should Know

TypeScript has become an indispensable tool for modern web development. As a superset of JavaScript, it adds static typing, improved developer tooling, and enhanced code readability to the JavaScript ecosystem. If you're a developer aiming to build scalable and maintainable applications, understanding TypeScript's core concepts is essential. This blog will guide you through the fundamentals that form the backbone of TypeScript.


1. What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft. It builds upon JavaScript by adding optional static types. This means you can define the types of variables, function parameters, and return values, enabling type-checking at compile-time.

Key Benefits:

  • Early error detection.
  • Enhanced IDE support with autocompletion and refactoring.
  • Easier collaboration in large teams.

2. Type Annotations and Inference

Type Annotations

TypeScript allows you to explicitly specify the type of a variable or function parameter:

let username: string = "John";
let age: number = 25;

function greet(name: string): string {
  return `Hello, ${name}`;
}
Enter fullscreen mode Exit fullscreen mode

Type Inference

In many cases, TypeScript can automatically infer the type based on the value assigned:

let isActive = true; // Inferred as boolean
Enter fullscreen mode Exit fullscreen mode

3. Interfaces and Types

Interfaces

Interfaces are used to define the shape of an object:

interface User {
  id: number;
  name: string;
}

const user: User = { id: 1, name: "Alice" };
Enter fullscreen mode Exit fullscreen mode

Type Aliases

Type aliases are similar to interfaces but can represent more complex types:

type UserID = string | number;
Enter fullscreen mode Exit fullscreen mode

Use interfaces for defining objects and type aliases for more flexible type definitions.


4. Enums

Enums allow you to define a set of named constants:

enum Role {
  Admin,
  User,
  Guest,
}

const userRole: Role = Role.Admin;
Enter fullscreen mode Exit fullscreen mode

5. Generics

Generics enable the creation of reusable components by allowing types to be passed as parameters:

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

const num = identity<number>(42);
const str = identity<string>("Hello");
Enter fullscreen mode Exit fullscreen mode

6. Union and Intersection Types

Union Types

Union types allow variables to hold values of different types:

let value: string | number;
value = "Hello";
value = 42;
Enter fullscreen mode Exit fullscreen mode

Intersection Types

Intersection types combine multiple types into one:

type Person = { name: string };
type Employee = { id: number };

type Staff = Person & Employee;
const staff: Staff = { name: "Bob", id: 123 };
Enter fullscreen mode Exit fullscreen mode

7. Modules and Namespaces

TypeScript supports ES6 modules for code organization:

// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

// app.ts
import { add } from "./math";
console.log(add(2, 3));
Enter fullscreen mode Exit fullscreen mode

Namespaces (deprecated in modern TypeScript) were used for organizing code before ES6 modules:

namespace Utils {
  export function log(message: string): void {
    console.log(message);
  }
}

Utils.log("Hello, Namespace!");
Enter fullscreen mode Exit fullscreen mode

8. Advanced Types

Mapped Types

Mapped types allow you to create new types by transforming existing ones:

type Readonly<T> = {
  readonly [K in keyof T]: T[K];
};

interface User {
  id: number;
  name: string;
}

const readonlyUser: Readonly<User> = { id: 1, name: "Alice" };
Enter fullscreen mode Exit fullscreen mode

Conditional Types

Conditional types provide type logic:

type IsString<T> = T extends string ? true : false;

type Result = IsString<number>; // false
Enter fullscreen mode Exit fullscreen mode

9. Decorators

Decorators are a feature of TypeScript used to modify classes, methods, or properties. They’re often seen in frameworks like Angular:

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

class Person {
  @Log
  sayHello() {
    console.log("Hello!");
  }
}
Enter fullscreen mode Exit fullscreen mode

10. Tooling and Configuration

tsconfig.json

TypeScript projects are configured using a tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode

Popular Tools

  • TSC: TypeScript Compiler.
  • ESLint: For linting TypeScript code.
  • Prettier: For code formatting.
  • TypeScript Plugin: Enhances editor support in VSCode and other IDEs.

Conclusion

TypeScript empowers developers to write robust, maintainable, and scalable applications. By understanding its core concepts, you can unlock its full potential and dramatically improve your development experience. Whether you're building small scripts or enterprise-level applications, TypeScript is a valuable addition to your toolkit.

Ready to level up your development skills? Start integrating TypeScript into your projects today!

Top comments (0)