YouTip LogoYouTip

Ts Features

TypeScript Features \n\n

TypeScript Features

\n\n

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

\n\n

Some key features of TypeScript:

\n\n
    \n
  • Static Type Checking: TypeScript checks whether types in code match at compile time, and can discover many potential errors. Even simple errors (such as typos or type mismatches) can be caught while writing code.
  • \n\n
  • Type Inference: TypeScript can automatically infer the type of variables. For example, when you declare a variable and assign a value, TypeScript will infer the variable's type based on the assignment, without needing to explicitly declare the type every time.
  • \n\n
  • Interfaces and Type Definitions: TypeScript provides interface and type keywords, allowing you to define complex data structures. This is very important for collaboration and data interaction between different parts of a project.
  • \n\n
  • Class and Module Support: TypeScript supports the class concept in object-oriented programming, adding constructors, inheritance, access control modifiers (such as public, private, protected), and supports ES module specifications.
  • \n\n
  • Tool and Editor Support: TypeScript has excellent editor support, especially when integrated with Visual Studio Code, providing intelligent hints, auto-completion, refactoring and other tools to make the development process more efficient.
  • \n\n
  • 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 complete rewriting.
  • \n
\n\n

Here are the main features TypeScript adds:

\n\n

1. Static Types

\n\n

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, which can catch many potential type errors at compile time. Common types include number, string, boolean, array, tuple, enum, etc., and custom types are also supported.

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

2. Type Inference

\n\n

TypeScript can automatically infer variable types. Even without explicitly declaring types, TypeScript will infer the type based on the variable's assignment content, thus reducing the amount of type annotation writing in most cases.

\n\n
let name = "Alice"; // inferred as string
\n\n

3. Interfaces (Interfaces)

\n\n

TypeScript provides interfaces, allowing complex object structures to be defined. Interfaces can define properties and methods, and can also implement interfaces with the implements keyword, or extend them with extends, making it easy to define complex data types.

\n\n
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}`); }}
\n\n

4. Type Aliases (Type Aliases)

\n\n

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

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

5. Enums (Enums)

\n\n

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

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

6. Tuples (Tuples)

\n\n

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

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

7. Access Modifiers (Access Modifiers)

\n\n

TypeScript provides public, private, and protected modifiers in classes, allowing control over the visibility of properties or methods, supporting better encapsulation.

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

8. Abstract Classes (Abstract Classes)

\n\n

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

\n\n
abstract class Animal { abstract makeSound(): void;}class Dog extends Animal { makeSound() { console.log("Woof!"); }}
\n\n

9. Generics (Generics)

\n\n

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

\n\n
function identity<T>(value: T): T { return value;}let num = identity<number>(42);
\n\n

10. Modules and Namespaces

\n\n

TypeScript provides an ES6-based module system, using import and export to import and export modules. Additionally, TypeScript supports namespaces (Namespace) for organizing code and avoiding naming conflicts.

\n\n
// math.tsexport function add(a: number, b: number): number { return a + b;}// main.tsimport { add } from "./math"; console.log(add(2, 3));
\n\n

11. Type Guards (Type Guards)

\n\n

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

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

12. Optional Chaining and Nullish Coalescing Operators

\n\n

TypeScript adds JavaScript's optional chaining (?.) and nullish coalescing operator (??), simplifying the handling of values that may be null or undefined in code.

\n\n
let user = { name: "Alice", address: { city: "Wonderland" } }; console.log(user?.address?.city); // if address exists, output city, otherwise return undefinedlet value = null; console.log(value ?? "default"); // if value is null or undefined, return "default"
\n\n

13. Type Compatibility and Utility Types

\n\n

TypeScript provides some utility types, such as Partial, Pick, Readonly, Record, etc. These types can help generate new types, simplifying type definitions.

\n\n
interface Todo { title: string; description: string;}let partialTodo: Partial<Todo> = { title: "Learn TypeScript" }; // optional properties
\n\n

14. Compile-time Error Checking

\n\n

TypeScript's compile-time error checking can catch errors that are not easily found in JavaScript, such as typos, type mismatches, etc., helping to improve code quality.

\n\n

15. ES New Features Support

\n\n

TypeScriptahead of timesupport(aspect particle indicating completed action or change of state)some not yet in all environments widely adopted (possessive particle) ES features,such asDecorators(Decorators)、asynchronousiteratorsetc. / and so on,andcanthemcompile tocompatible JavaScript versions。

\n\n

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

← Sql InjectionJava Constructor β†’