TypeScript是一种开源编程语言。它是JavaScript的一个超集,添加了可选的静态类型和基于类的面向对象编程等特性。TypeScript旨在开发大型应用程序,并最终编译为JavaScript以在浏览器或其他JavaScript环境中运行。以下是TypeScript的一些基础知识点:
1. 类型注解(Type Annotations)
TypeScript允许你在变量、函数参数和函数返回值旁边添加类型注解,以明确它们的预期类型。这有助于在编译时捕获类型错误。
let name: string = "John Doe";
let age: number = 30;
let isActive: boolean = true;
function greet(name: string): string {
return "Hello, " + name;
}
2. 接口(Interfaces)
接口是TypeScript的核心原则之一,用于定义对象的形状。接口可以包含属性和方法的声明。
interface Person {
name: string;
age: number;
greet(): void;
}
let user: Person = {
name: "Jane Doe",
age: 25,
greet() {
console.log("Hello, " + this.name);
}
};
3. 类(Classes)
TypeScript支持基于类的面向对象编程。类可以实现接口,并支持继承、封装和多态等概念。
class Employee {
private name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello, " + this.name);
}
}
class Manager extends Employee {
constructor(name: string, age: number) {
super(name, age);
}
delegateWork() {
console.log("Delegating tasks");
}
}
4. 泛型(Generics)
泛型提供了一种方式来创建可重用的组件,这些组件可以与多种类型一起工作,而不会丢失其原始类型。
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
5. 枚举(Enums)
枚举是一种特殊的类,它更多地关注于值而不是类型。枚举用于定义一组命名常量。
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
6. 模块(Modules)
TypeScript支持模块,允许你将代码分割成可重用的单元。模块可以导出或导入其他模块。
// file: math.ts
export function add(x: number, y: number): number {
return x + y;
}
// file: app.ts
import { add } from "./math";
console.log(add(5, 3));
7. 装饰器(Decorators)
装饰器是一种特殊类型的声明,它可以被附加到类声明、方法、访问符、属性或参数上。装饰器使用@expression形式,expression求值后必须为一个函数,它会在运行时被调用。
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
8. 联合类型和交叉类型(Union and Intersection Types)
联合类型表示一个值可以是几种类型之一。交叉类型是将多个类型合并为一个类型。
type StringOrNumber = string | number;
type StudentAndEmployee = Student & Employee;
function printId(id: StringOrNumber) {
console.log("Your ID is: " + id);
}
9. 类型守卫和类型断言(Type Guards and Type Assertions)
类型守卫用于确保变量属于某个特定类型。类型断言则是告诉编译器,你知道这个变量的类型。
function isString(test: any): test is string {
return typeof test === "string";
}
function example(foo: any) {
if (isString(foo)) {
console.log("it is a string" + foo);
}
// 类型断言
let strLength: number = (<string>foo).length;
let strLengthAs: number = (foo as string).length;
}
TypeScript的这些基础知识点为开发大型、可维护的JavaScript应用程序提供了强大的工具和概念。通过使用TypeScript,开发者可以享受到强类型语言的好处,同时保持JavaScript的灵活性和表达力。
212

被折叠的 条评论
为什么被折叠?



