TypeScript 关键字归纳

一、变量声明

  • let: 用于声明可变变量。
  • var: 用于声明变量(不建议使用)。
  • const: 用于声明不可变变量。
ts 复制代码
// 使用 let 声明可变变量
let age: number = 25;
age = 26; // 可以重新赋值

// 使用 var 声明变量(不建议使用)
var score: number = 100;
score = 95; // 可以重新赋值
// var 在块级作用域外仍然可见,容易引发问题
if (true) {
    var localVar = "I am a local variable with var.";
}
console.log(localVar); // localVar 在块级作用域外仍然可访问

// 使用 const 声明不可变变量
const name: string = "Alice";
// name = "Bob"; // 尝试重新赋值会导致编译错误

// 使用 const 声明对象,对象内部属性仍然可以修改
const person = { firstName: "John", lastName: "Doe" };
person.firstName = "Jane"; // 可以修改对象的属性

二、基础类型

  • number: 表示数字类型。
  • string: 表示字符串类型。
  • boolean: 表示布尔类型。
ts 复制代码
// 使用 number 声明数字类型变量
let age: number = 30;
let price: number = 19.99;

// 使用 string 声明字符串类型变量
let name: string = "Alice";
let greeting: string = `Hello, ${name}!`;

// 使用 boolean 声明布尔类型变量
let isLogged: boolean = true;
let isRegistered: boolean = false;
  • null: 表示空值。
  • undefined: 表示未定义的值。
ts 复制代码
// 使用 null 表示空值
let nullValue: null = null;
let nullableNumber: number | null = null; // 可以是数字或 null

// 使用 undefined 表示未定义的值
let undefinedValue: undefined = undefined;
let undefinableString: string | undefined = undefined; // 可以是字符串或 undefined
  • any: 表示动态类型,可以包含任何类型的值。
ts 复制代码
let dynamicValue: any = 42;
dynamicValue = "Hello, TypeScript!";
dynamicValue = true;
  • void: 表示没有返回值的函数。
ts 复制代码
function sayHello(): void {
    console.log("Hello, void!");
}
// 函数没有返回值
  • never: 表示永不返回值的函数。
ts 复制代码
function throwError(message: string): never {
    throw new Error(message);
}
// 函数抛出异常,不会正常返回
  • unknown: 表示未知类型。
ts 复制代码
let userInput: unknown = "Hello, unknown!";
let userName: string;

// 需要进行类型检查或类型断言
if (typeof userInput === "string") {
    userName = userInput; // 进行类型检查后才能赋值
}

三、复合类型

JavaScript 中是包装类型:

  • Number: 包装对象类型。
ts 复制代码
let numObject: Number = new Number(42);
console.log(numObject.valueOf()); // 42

// 注意:不建议使用包装对象,通常使用基本数据类型 number 更加方便和高效
let numPrimitive: number = 42;
  • Boolean: 包装对象类型。
ts 复制代码
let boolObject: Boolean = new Boolean(true);
console.log(boolObject.valueOf()); // true

// 同样,不建议使用包装对象,通常使用基本数据类型 boolean 更加方便和高效
let boolPrimitive: boolean = true;
  • Array: 表示数组类型。
ts 复制代码
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: Array<string> = ["apple", "banana", "cherry"];
  • Object: 表示对象类型。
ts 复制代码
let person: { name: string; age: number } = { name: "Alice", age: 30 };
let book: { title: string; author: string } = { title: "The Catcher in the Rye", author: "J.D. Salinger" };
  • String: 包装对象类型。
ts 复制代码
let strObject: String = new String("Hello, TypeScript!");
console.log(strObject.valueOf()); // "Hello, TypeScript!"

// 同样,不建议使用包装对象,通常使用基本数据类型 string 更加方便和高效
let strPrimitive: string = "Hello, TypeScript!";
  • Function: 表示函数类型。
ts 复制代码
let add: Function = (a: number, b: number) => a + b;
let greet: Function = (name: string) => `Hello, ${name}!`;

// 使用函数类型声明函数参数和返回值类型
function calculate(operation: Function, a: number, b: number): number {
    return operation(a, b);
}
console.log(calculate(add, 5, 3)); // 8
console.log(calculate(greet, "Alice", "")); // "Hello, Alice!"

四、控制流-循环关键字

  • if: 条件语句,用于执行条件判断。
  • else: 条件语句的分支,用于在条件不满足时执行的代码。
ts 复制代码
let age: number = 25;

// 使用 if 条件语句执行条件判断
if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are not yet an adult.");
}
  • case/switch: 在 switch 语句中用于定义不同的分支。
ts 复制代码
let day: number = 3;
let dayName: string;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    //...
    default:
        dayName = "Invalid day"; // 当没有匹配的 case 时执行 default 分支
        break;
}

console.log(`Today is ${dayName}`);
  • for/for-in/for-of: 循环语句,用于迭代一个范围内的值。
  • break: 用于跳出循环或 switch 语句。
  • continue: 用于跳过当前循环的剩余部分并进入下一次迭代。
ts 复制代码
// 循环数据
for (let i = 1; i <= 5; i++) {
    console.log(`Iteration ${i}`);
}

// break 跳出循环
for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break; // 当 i 等于 5 时跳出循环
    }
    console.log(`Iteration ${i}`);
}

// 继续循环
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue; // 当 i 等于 3 时跳过此次迭代
    }
    console.log(`Iteration ${i}`);
}

// 遍历对象
const person = {
    name: "Alice",
    age: 30,
    city: "New York"
};

for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}

// 迭代数组
const numbers = [1, 2, 3, 4, 5];

for (let num of numbers) {
    console.log(`Number: ${num}`);
}
  • do/while: 用于创建一个在条件为真时重复执行的循环。
ts 复制代码
let count: number = 0;

do {
    console.log(`Count: ${count}`);
    count++;
} while (count < 5);

五、函数相关

  • function/return: 用于声明函数。
  • =>(箭头函数): 用于定义匿名函数。
ts 复制代码
// 函数声明
function add(a: number, b: number): number {
    return a + b;
}

// 箭头函数
const multiply = (x: number, y: number): number => x * y;

六、类

  • class: 用于声明类。
  • constructor: 用于定义类的构造函数。
  • new: 实例化class
  • extends: 用于实现继承。
  • super: 用于调用父类构造函数或方法。
  • instanceof: 用于检查对象是否是某个类的实例。
  • this: 用于引用当前类的实例。
ts 复制代码
// 基类 Animal
class Animal {
    constructor(name: string) {
        this.name = name;
    }

    // 基类方法
    eat(food: string): void {
        console.log(`${this.name} is eating ${food}`);
    }
}

// 继承 Animal 的 Bird 类
class Bird extends Animal {
    constructor(name: string, canFly: boolean) {
        super(name); // 调用基类的构造函数
        this.canFly = canFly;
    }

    // Bird 特有方法
    fly(): void {
        if (this.canFly) {
            console.log(`${this.name} is flying.`);
        } else {
            console.log(`${this.name} cannot fly.`);
        }
    }
}

// 继承 Animal 的 Dog 类
class Dog extends Animal {
    constructor(name: string, breed: string) {
        super(name); // 调用基类的构造函数
        this.breed = breed;
    }

    // Dog 特有方法
    bark(): void {
        console.log(`${this.name} (${this.breed}) is barking.`);
    }
}

// 实例化 Bird 和 Dog 对象
const eagle = new Bird("Eddie", true);
const penguin = new Bird("Penny", false);
const labrador = new Dog("Buddy", "Labrador");
const poodle = new Dog("Fluffy", "Poodle");

// 检查对象是否是特定类的实例
console.log(eagle instanceof Bird); // true
console.log(eagle instanceof Animal); // true
console.log(labrador instanceof Dog); // true
console.log(labrador instanceof Animal); // true

七、枚举

  • enum: 用于创建枚举类型。
ts 复制代码
// 定义一个枚举类型 DaysOfWeek
enum DaysOfWeek {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

// 声明一个变量并将其设置为枚举值
let today: DaysOfWeek = DaysOfWeek.Wednesday;

// 使用枚举值
switch (today) {
    case DaysOfWeek.Sunday:
        console.log("今天是星期日");
        break;
    case DaysOfWeek.Monday:
        console.log("今天是星期一");
        break;
    case DaysOfWeek.Wednesday:
        console.log("今天是星期三");
        break;
    default:
        console.log("今天不是星期日、星期一或星期三");
}

八、接口与实现

  • interface: 用于定义接口。
  • implements: 用于实现接口。
  • abstract: 用于声明抽象类或方法。
ts 复制代码
// 定义一个接口
interface Shape {
    calculateArea(): number;
}

// 实现接口的类 Circle
class Circle implements Shape {
    constructor(private radius: number) {}

    // 实现接口中的方法
    calculateArea(): number {
        return Math.PI * this.radius ** 2;
    }
}

// 实现接口的类 Square
class Square implements Shape {
    constructor(private sideLength: number) {}

    // 实现接口中的方法
    calculateArea(): number {
        return this.sideLength ** 2;
    }
}

// 抽象类 Animal
abstract class Animal {
    constructor(public name: string) {}

    // 声明抽象方法
    abstract makeSound(): void;
}

// 继承抽象类 Animal 的类 Dog
class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }

    // 实现抽象方法
    makeSound(): void {
        console.log(`${this.name} barks.`);
    }
}

// 使用接口和抽象类的实例
const circle = new Circle(5);
const square = new Square(4);
const dog = new Dog("Buddy");

console.log(`Circle Area: ${circle.calculateArea()}`);
console.log(`Square Area: ${square.calculateArea()}`);
dog.makeSound();

九、类型

  • type: 用于创建类型别名。

十、类型推断

  • as: 用于类型断言。
  • ![操作符](非空断言): 用于告诉 TypeScript 一个值一定不为 null 或 undefined。
  • as const 的特殊用法: 用于创建只读的字面量类型。
  • satisfies: 满意性推断
ts 复制代码
// 创建一个类型别名
type Point = {
    x: number;
    y: number;
};

// 声明一个函数,参数和返回值使用类型别名
function calculateDistance(point1: Point, point2: Point): number {
    const deltaX = point1.x - point2.x;
    const deltaY = point1.y - point2.y;
    return Math.sqrt(deltaX ** 2 + deltaY ** 2);
}

// 使用类型别名声明变量
const pointA: Point = { x: 0, y: 0 };
const pointB: Point = { x: 3, y: 4 };

// 调用函数并使用类型别名
const distance = calculateDistance(pointA, pointB);

console.log(`点A到点B的距离是: ${distance}`);
  • satisfies
ts 复制代码
// 定义一个接口 WeekDay,表示星期几的名称
interface WeekDay {
    day: "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday";
}

// 创建一个对象 dayInWeek,满足 WeekDay 接口的定义
const dayInWeek = {
    day: "Monday", // 例如,表示今天是星期一
} satisfies WeekDay;

// 访问 dayInWeek 的属性
console.log(`Today is ${dayInWeek.day}`);

dayInWeek 注意 dayInWeek 不再直接注释类型,而是在后面 satisfies WeekDay

十一、命名空间

  • namespace: 用于创建命名空间。
  • readonly: 用于声明只读属性。
  • public: 用于指定属性或方法为公有。
  • private: 用于指定属性或方法为私有。
  • protected: 用于指定属性或方法为受保护的。
  • static: 用于声明静态属性或方法。
  • declare: 用于告诉 TypeScript 某个变量的类型已经在其他地方声明。
ts 复制代码
// 创建命名空间 MyNamespace
namespace MyNamespace {
    // 声明一个只读属性
    export const pi: number = 3.14159265358979323846;

    // 声明一个类
    export class Rectangle {
        constructor(public width: number, public height: number) {}

        // 声明一个公有方法
        public calculateArea(): number {
            return this.width * this.height;
        }

        // 声明一个私有方法
        private logDimensions(): void {
            console.log(`Width: ${this.width}, Height: ${this.height}`);
        }
    }

    // 声明一个抽象类
    export abstract class Shape {
        constructor(public name: string) {}

        // 声明一个抽象方法
        abstract displayArea(): void;

        // 声明一个静态属性
        static description: string = "This is a shape.";
    }

    // 使用 declare 声明变量类型
    declare let externalLibraryVariable: any;
}

// 使用命名空间中的成员
const circleArea = MyNamespace.pi * 5 * 5;
console.log(`Circle Area: ${circleArea}`);

const rectangle = new MyNamespace.Rectangle(4, 6);
console.log(`Rectangle Area: ${rectangle.calculateArea()}`);

const shape = new MyNamespace.Shape("MyShape");
console.log(`Shape Name: ${shape.name}`);
console.log(MyNamespace.Shape.description);

// 尝试访问私有方法(编译时会报错)
// rectangle.logDimensions();

// 使用 declare 声明的外部变量
declare const externalLibraryVariable: number;
console.log(`External Library Variable: ${externalLibraryVariable}`);

十二、模块

  • import/export: 用于模块导入和导出。
ts 复制代码
// MathOperations.ts 模块
export function add(a: number, b: number): number {
    return a + b;
}

export function subtract(a: number, b: number): number {
    return a - b;
}
ts 复制代码
// 导入 MathOperations 模块中的函数
import { add, subtract } from './MathOperations';

const result1 = add(5, 3);
console.log(`5 + 3 = ${result1}`);

const result2 = subtract(10, 4);
console.log(`10 - 4 = ${result2}`);

十三、获取 key

  • keyof: 用于获取对象类型的键。
ts 复制代码
// 定义一个对象类型
type Person = {
    name: string;
    age: number;
    address: string;
};

// 使用 keyof 获取 Person 对象类型的键的类型
type PersonKeys = keyof Person;

// 声明一个变量使用 PersonKeys 类型
let key: PersonKeys;

// 尝试赋予 key 一个非法的值(编译时会报错)
// key = "email";

// 正确赋值,key 只能是 "name"、"age" 或 "address" 中的一个
key = "name"; 

// 使用 key 获取对象属性的值
const person: Person = {
    name: "Alice",
    age: 30,
    address: "123 Main St"
};

const propertyName: PersonKeys = "age";
const propertyValue = person[propertyName];
console.log(`Property name: ${propertyName}, Property value: ${propertyValue}`);

十四、提取已知类型

  • infer: 用于从类型中提取特定的类型。
ts 复制代码
// 定义一个泛型函数,它接受一个函数作为参数
function getResult<T>(callback: () => T): T {
    return callback();
}

// 使用 infer 提取返回值类型,并分配给新的类型参数
type ResultType<T> = T extends () => infer R ? R : never;

// 声明一个变量并使用泛型函数
const numberResult: ResultType<number> = getResult(() => 42);
const stringResult: ResultType<string> = getResult(() => "Hello, TypeScript!");

console.log(`Number result: ${numberResult}`);
console.log(`String result: ${stringResult}`);

十五、异步

  • async/await: 用于处理异步操作。
ts 复制代码
// 模拟一个异步函数,返回一个 Promise
function fetchData(): Promise<string> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data fetched successfully!");
        }, 2000);
    });
}

// 使用 async 和 await 处理异步操作
async function fetchDataAsync() {
    try {
        console.log("Fetching data...");
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error("Error fetching data:", error);
    }
}

// 调用异步函数
fetchDataAsync();
console.log("Async operation in progress...");

十六、错误相关

  • try/catch: 用于捕获和处理异常。
  • throw: 用于抛出异常。
ts 复制代码
// 定义一个函数,它会抛出异常
function divide(x: number, y: number): number {
    if (y === 0) {
        throw new Error("Division by zero is not allowed.");
    }
    return x / y;
}

// 使用 try/catch 处理异常
function divideSafely(x: number, y: number): string {
    try {
        const result = divide(x, y);
        return `Result: ${result}`;
    } catch (error) {
        return `Error: ${error.message}`;
    }
}

// 调用函数并处理异常
console.log(divideSafely(10, 2)); // 正常情况
console.log(divideSafely(10, 0)); // 异常情况

十七、小结

本文主要总结 TypeScript 中关键字和部分相关的操作符。

相关推荐
骆晨学长6 分钟前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
AskHarries11 分钟前
利用反射实现动态代理
java·后端·reflect
世俗ˊ17 分钟前
CSS入门笔记
前端·css·笔记
子非鱼92117 分钟前
【前端】ES6:Set与Map
前端·javascript·es6
6230_22 分钟前
git使用“保姆级”教程1——简介及配置项设置
前端·git·学习·html·web3·学习方法·改行学it
想退休的搬砖人31 分钟前
vue选项式写法项目案例(购物车)
前端·javascript·vue.js
Flying_Fish_roe35 分钟前
Spring Boot-Session管理问题
java·spring boot·后端
加勒比海涛1 小时前
HTML 揭秘:HTML 编码快速入门
前端·html
啥子花道1 小时前
Vue3.4 中 v-model 双向数据绑定新玩法详解
前端·javascript·vue.js
麒麟而非淇淋1 小时前
AJAX 入门 day3
前端·javascript·ajax