TypeScript 是 JavaScript 的超集,它添加了静态类型系统,能在开发阶段捕获类型错误,提升代码可维护性和可读性。以下是 TypeScript 在 JavaScript 项目中的常见使用案例:
为变量、函数参数和返回值指定类型,避免类型混淆。
// 变量类型定义
let username: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
// 函数类型定义(参数类型 + 返回值类型)
function add(a: number, b: number): number {
return a + b;
}
// 错误示例(编译时会报错)
add("1", 2); // 类型“string”的参数不能赋给类型“number”的参数
用于约束对象的形状,尤其适合前后端数据交互时定义接口返回格式。
// 定义用户数据结构
interface User {
id: number;
name: string;
email?: string; // 可选属性
readonly role: "admin" | "user"; // 只读属性 + 联合类型
}
// 符合接口约束的对象
const user: User = {
id: 1,
name: "Bob",
role: "user"
};
// 错误示例(缺少必填属性或类型不匹配)
const invalidUser: User = {
id: "1", // 类型“string”不能赋给类型“number”
name: "Bob"
// 缺少 role 属性,编译报错
};
结合接口实现更严格的类结构约束,支持访问修饰符(public/private/protected)。
interface Person {
getName(): string;
}
class Student implements Person {
private id: number; // 私有属性,仅类内部可访问
public name: string; // 公共属性,默认可省略 public
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
getName(): string {
return this.name;
}
private getStudentId(): number {
return this.id; // 私有方法,仅类内部可调用
}
}
const student = new Student(101, "Charlie");
console.log(student.getName()); // 正确
console.log(student.id); // 错误:属性“id”为私有属性,只能在类“Student”中访问
用于创建可重用的组件,支持多种类型而不丢失类型信息(类似“类型变量”)。
// 泛型函数:交换数组中两个元素的位置
function swap<T>(arr: T[], i: number, j: number): T[] {
const copy = [...arr];
[copy[i], copy[j]] = [copy[j], copy[i]];
return copy;
}
// 支持 number 数组
const numbers = [1, 2, 3];
swap(numbers, 0, 1); // 正确,返回 [2, 1, 3]
// 支持 string 数组
const strings = ["a", "b", "c"];
swap(strings, 0, 1); // 正确,返回 ["b", "a", "c"]
处理“可能为多种类型”的场景,通过类型守卫缩小类型范围。
// 联合类型:value 可能是 string 或 number
function formatValue(value: string | number): string {
// 类型守卫:判断 value 是否为 string
if (typeof value === "string") {
return value.toUpperCase(); // 此时 TypeScript 知道 value 是 string
}
// 否则 value 一定是 number
return value.toFixed(2); // 安全调用 number 方法
}
formatValue("hello"); // "HELLO"
formatValue(3.1415); // "3.14"
在模块化项目中管理类型,对第三方库(无 TypeScript 类型)添加类型声明。
// user.ts(模块)
export interface User {
id: number;
name: string;
}
// api.ts(使用模块)
import { User } from "./user";
export function fetchUser(): Promise<User> {
return fetch("/api/user").then(res => res.json());
}
// 对无类型的第三方库添加声明(如在 global.d.ts 中)
declare module "some-js-library" {
export function doSomething(arg: string): boolean;
}
为组件 props、状态(state)和事件添加类型约束,减少运行时错误。
import React, { useState } from "react";
// 定义组件 props 类型
interface CounterProps {
initialValue?: number;
label: string;
}
const Counter: React.FC<CounterProps> = ({ initialValue = 0, label }) => {
// 定义状态类型(TypeScript 可自动推断,但显式声明更清晰)
const [count, setCount] = useState<number>(initialValue);
return (
<div>
<p>{label}: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
};
// 使用组件时,TypeScript 会检查 props 是否符合类型
<Counter label="Score" />; // 正确
<Counter initialValue="10" label="Score" />; // 错误:initialValue 应为 number
TypeScript 可以逐步引入 JavaScript 项目(通过 allowJs
配置),适合从无类型的旧项目平滑迁移。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。