Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Features

TypeScript Features

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

Some key features of TypeScript:

The following are the main features added by TypeScript:

1. Static Typing

TypeScript's biggest feature is the addition of a static type system. In TypeScript, developers can explicitly declare the types of variables, parameters, and return values, catching many potential type errors at compile time. Common types include number、string、boolean、array、tuple、enum , 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 explicit type declarations, TypeScript infers types from the assigned values, reducing the amount of type annotations needed in most cases.

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

3. Interfaces

TypeScript provides interfaces, allowing you to define complex object structures. Interfaces can define properties and methods, and can also use the implements keyword to implement an interface, or use extends for extension, making it easy to define 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 alias (type) can define a short alias for a complex type, facilitating code reuse.

type StringOrNumber = string | number;

let value: StringOrNumber = 42;

5. Enums

TypeScript introduces the enum type, used to define a set of named constants and improve code readability. Enums have no direct counterpart in JavaScript.

enum Direction {

  Up,

  Down,

  Left,

  Right,

}

let dir: Direction = Direction.Up;

6. Tuples

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

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

7. Access Modifiers

TypeScript provides the public、private and protected modifiers 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, which cannot be instantiated directly and must be implemented by subclasses. Abstract classes are suitable for class hierarchies that define 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, so code can adapt to different type requirements while maintaining type safety.

function identity(value: T): T {

  return value;

}



let num = identity(42);

10. Modules and namespaces

TypeScript provides an ES6-based module system, using import and export to import and export modules. In addition, TypeScript supports namespaces (Namespace) 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 that check variable types in code, helping 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 the nullish coalescing operator (??), simplifying the handling of values that may be null or undefined null or undefined.

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 several utility types, such as Partial、Pick、Readonly、Record , which help generate new types and simplify type definitions.

interface Todo {

  title: string;

  description: string;

}



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

14. Compile-time error checking

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

15. Support for new ES features

TypeScript supports some ES features ahead of their widespread adoption, such as decorators (Decorators) and async iterators, and can compile them into compatible JavaScript versions.

Through these features, TypeScript provides safer and more structured code capabilities, with particular advantages in large projects and multi-person collaboration.