📜  代码 - TypeScript (1)

📅  最后修改于: 2023-12-03 14:49:29.868000             🧑  作者: Mango

TypeScript

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. However, TypeScript provides additional features such as static typing, interfaces, classes, and modules that aid in building large and complex applications.

Features
Static Typing

TypeScript supports static typing, allowing you to specify the data type of variables, function parameters, and function return values. This helps catch type-related errors at compile time, preventing runtime errors.

let message: string = "Hello, world!";
let age: number = 28;
let isStudent: boolean = true;
Interfaces

Interfaces allow you to define the shape of an object, including its properties and their types. This helps ensure that objects passed between functions or modules have the required properties and types.

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}

function greet(person: Person): void {
  console.log(`Hello, ${person.firstName} ${person.lastName}! You are ${person.age} years old.`);
}

let person1 = { firstName: "John", lastName: "Doe", age: 30 };
greet(person1); // Output: Hello, John Doe! You are 30 years old.
Classes

Classes allow you to create reusable object blueprints with their own properties and methods. TypeScript supports inheritance, abstract classes, and access modifiers.

class Animal {
  protected name: string;
   constructor(name: string) {
    this.name = name;
  }
  public move(distance: number = 0) {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }
  public bark() {
    console.log(`${this.name} barked!`);
  }
}

let dog1 = new Dog("Fido");
dog1.bark(); // Output: Fido barked!
dog1.move(10); // Output: Fido moved 10 meters.
Modules

TypeScript supports modules, allowing you to organize your code into separate files. Modules are imported and exported using the import and export keywords, respectively.

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

// main.ts
import { add } from "./utils";
let result = add(1, 2); // result = 3
Conclusion

TypeScript is a powerful tool that can help you write cleaner, more maintainable JavaScript code. Whether you're building a small website or a large enterprise application, TypeScript can help you catch errors early, make your code more readable, and reduce the likelihood of bugs.