TypeScript Features
Compared with 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, discovering many potential errors. Even simple mistakes (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 a value, TypeScript infers the variable's type from the assignment, so you don't need to explicitly declare the type every time.
-
Interfaces and type definitions: TypeScript provides the
interfaceandtypekeyword, allowing you to define complex data structures. This is very important for code collaboration and data interaction between different parts of a project. -
Classes and module support: TypeScript supports the concept of classes in object-oriented programming, adding constructors, inheritance, access control modifiers (such as
public、private、protected), and supports ES module specifications. -
Tooling and editor support: TypeScript has good editor support, especially when integrated with Visual Studio Code, providing tools such as IntelliSense, auto-completion, and refactoring to make development more efficient.
-
JavaScript compatibility: TypeScript is a superset of JavaScript, which means 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 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.