TypeScript Features

Compared to JavaScript, TypeScript adds many key features, especially enhancements around the type system and code structure.

Some key features of TypeScript:

  • Static type checking: TypeScript checks whether code types match at compile time, catching many potential errors. Even simple errors (such as typos or type inconsistencies) can be caught while writing code.

  • Type inference: TypeScript can automatically infer variable types. For example, when you declare a variable and assign it a value, TypeScript infers the variable's type based on the assignment, so you don't need to explicitly declare types every time.

  • Interfaces and type definitions: TypeScript provides theinterfaceandtypekeyword, allowing you to define complex data structures. This is very important for code collaboration and data interaction between different parts of a project.

  • Class and module support: TypeScript supports the class concept from object-oriented programming, adding constructors, inheritance, access control modifiers (such aspublic、private、protected), and supports the ES module specification.

  • Tool and editor support: TypeScript has excellent editor support, especially when integrated with Visual Studio Code, providing IntelliSense, auto-completion, refactoring, and other tools, making development more efficient.

  • Compatible with JavaScript: TypeScript is a superset of JavaScript, meaning all valid JavaScript code is valid TypeScript code. This allows JavaScript projects to gradually migrate to TypeScript without a complete rewrite.

The following are the main features added by TypeScript:

1. Static types

TypeScript's biggest feature is the addition of a static type system. In TypeScript, developers can explicitly declare types for variables, parameters, and return values, allowing many potential type errors to be caught at compile time. Common types includenumber、string、boolean、array、tuple、enumetc., and custom types are also supported.

let name: string = "Alice";
let age: number = 25;

2. Type inference

TypeScript can automatically infer variable types. Even without explicitly declaring types, TypeScript infers types based on the assigned value, reducing the amount of type annotations needed in most cases.

let name = "Alice"; // 推断为 string

3. Interfaces

TypeScript provides interfaces, allowing complex object structures to be defined. Interfaces can define properties and methods, and can be implemented using theimplementskeyword, or extended throughextendsto facilitate defining complex data types.

interface Person {
  name: string;
  age: number;
  greet(): void;
}

class Student implements Person {
  constructor(public name: string, public age: number) {}

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

4. Type Aliases

Type aliases (type) can define short aliases for complex types, making code reuse easier.

type StringOrNumber = string | number;
let value: StringOrNumber = 42;

5. Enums

TypeScript introduces theenumtype, used to define a set of named constants, improving code readability. Enums have no direct equivalent in JavaScript.

enum Direction {
  Up,
  Down,
  Left,
  Right,
}
let dir: Direction = Direction.Up;

6. Tuples

Tuples allow defining arrays with a fixed number and types of elements. They are suitable for scenarios requiring fixed data structures, such as coordinates or RGB color values.

let point: [number, number] = [10, 20];

7. Access Modifiers

TypeScript provides thepublic、privateandprotectedmodifiers in classes, allowing control over the visibility of properties or methods and supporting better encapsulation.

class Person {
  private name: string;
  protected age: number;
  public constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

8. Abstract Classes

TypeScript supports abstract classes. Abstract classes cannot be instantiated directly and must be implemented by subclasses. Abstract classes are suitable for defining class hierarchies with common behavior and abstract methods.

abstract class Animal {
  abstract makeSound(): void;
}

class Dog extends Animal {
  makeSound() {
    console.log("Woof!");
  }
}

9. Generics

TypeScript supports generics, allowing parameterized types in classes, interfaces, and functions, enabling code to adapt to different type requirements while maintaining type safety.

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

let num = identity<number>(42);

10. Modules and namespaces

TypeScript provides an ES6-based module system, usingimportandexportto import and export modules. Additionally, TypeScript supports namespaces for organizing code and avoiding naming conflicts.

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

// main.ts
import { add } from "./math";
console.log(add(2, 3));

11. Type Guards

TypeScript provides type guards, which can check variable types in code and help the compiler infer more specific types. This is especially important for union types.

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(2));
  }
}

12. Optional chaining and nullish coalescing operators

TypeScript adds JavaScript's optional chaining (?.) and nullish coalescing operator (??), simplifying handling of potentiallynullorundefinedvalues in code.

let user = { name: "Alice", address: { city: "Wonderland" } };
console.log(user?.address?.city); // 如果 address 存在则输出 city,否则返回 undefined

let value = null;
console.log(value ?? "default"); // 如果 value 为 null 或 undefined,则返回 "default"

13. Type compatibility and utility types

TypeScript provides some utility types, such asPartial、Pick、Readonly、Recordetc. These types can help generate new types and simplify type definitions.

interface Todo {
  title: string;
  description: string;
}

let partialTodo: Partial<Todo> = { title: "Learn TypeScript" }; // 可选属性

14. Compile-time error checking

TypeScript's compile-time error checking can catch errors that are hard to spot in JavaScript, such as typos and type mismatches, helping improve code quality.

15. ES new feature support

TypeScript supports some ES features that are not yet widely available in all environments, such as decorators and async iterators, and can compile them into compatible JavaScript versions.

Through these features, TypeScript provides safer and more structured coding capabilities, which are especially advantageous in large projects and multi-person collaboration.

Other extensions