TS 使用泛型和 typeof约束参数

在 TypeScript(TS)中,泛型和 typeof 是两个强大的工具,可以帮助你创建更灵活和类型安全的代码。泛型允许你定义函数、接口或类时不具体指定类型,而 typeof 则用于获取一个变量或值的类型。

泛型

泛型允许你在定义函数、接口或类时,不指定具体的类型,而是在使用时指定。这样可以让你的代码更加灵活和可复用。

例如,定义一个简单的泛型函数:

typescript 复制代码
function identity<T>(arg: T): T {
    return arg;
}

// 使用泛型函数
const number = identity<number>(42); // 类型是 number
const text = identity<string>("Hello"); // 类型是 string

typeof

typeof 操作符用于获取一个变量或属性的类型。这在很多场景下都非常有用,比如当你需要根据一个现有变量的类型来定义另一个变量的类型时。

typescript 复制代码
const someNumber = 42;
type NumberType = typeof someNumber; // NumberType 是 number

const someString = "Hello";
type StringType = typeof someString; // StringType 是 string

泛型与 typeof 结合使用

有时候你可能需要定义一个泛型,但又要约束这个泛型参数的类型,使其只能是某个特定类型或某个特定对象的类型。这时,你可以将 typeof 与泛型结合使用。

约束泛型参数为特定对象的类型

假设你有一个对象,并希望定义一个函数,这个函数接受一个与这个对象类型相同的参数:

typescript 复制代码
const config = {
    apiUrl: "https://api.example.com",
    timeout: 5000
};

function printConfig<T extends typeof config>(cfg: T) {
    console.log(cfg.apiUrl);
    console.log(cfg.timeout);
}

// 正确使用
printConfig(config);

// 错误使用(如果尝试传入一个与 config 类型不兼容的对象)
// printConfig({ apiUrl: "https://wrong-url.com" }); // Error: Property 'timeout' is missing in type '{ apiUrl: string; }' but required in type 'typeof config'.

在这个例子中,泛型 T 被约束为 typeof config,这意味着 T 必须是与 config 相同类型的对象。

泛型与 typeof 结合用于类和方法

你也可以在类和方法中使用这种技巧:

typescript 复制代码
interface Config {
    apiUrl: string;
    timeout: number;
}

const defaultConfig: Config = {
    apiUrl: "https://api.example.com",
    timeout: 5000
};

class ApiClient<T extends typeof defaultConfig> {
    private config: T;

    constructor(config: T) {
        this.config = config;
    }

    getConfig() {
        return this.config;
    }
}

const client = new ApiClient(defaultConfig);
console.log(client.getConfig().apiUrl); // 输出: https://api.example.com

在这个例子中,ApiClient 类接受一个泛型参数 T,这个参数被约束为 typeof defaultConfig 的类型。这样,ApiClient 的实例将只能接受与 defaultConfig 相同类型的配置对象。

总结

通过将泛型与 typeof 结合使用,你可以创建更灵活和类型安全的 TypeScript 代码。这种技巧在处理配置对象、依赖注入和其他需要类型约束的场景中特别有用。

相关推荐
右耳朵猫AI6 天前
Web前端周刊2026W38 | React 19.3 发布、StyleX 深潜、jsdom 30.1 提速
前端·javascript·react.js·typescript·node.js
溪语流沙6 天前
Django + Vue电商项目第001讲:开篇|注册登录加增删改查,那不是电商
redis·python·mysql·docker·typescript·django·vue
掰头战士7 天前
多重影分身!恨不得把一个agent掰成两个? 还真能干!
typescript·llm·agent
shmily麻瓜小菜鸡7 天前
TDD(测试驱动开发)详解
开发语言·javascript·typescript·node.js·ecmascript
雾隐隐o8 天前
TypeScript 基础:数据类型、接口与类型推论
typescript
flash俊杰8 天前
Zod Schema 驱动的 IPC 契约:从入参校验到状态机一致性的三层防御
javascript·typescript
愛芳芳8 天前
基于 Electron + Vue3 的仿 PC 微信客户端项目实战
前端·javascript·css·elementui·typescript·electron·vue
神秘的猪头9 天前
TypeScript 高级用法全解析:从泛型到 infer,把类型系统真正用起来
前端·typescript
FYKJ_20109 天前
【毕设分享】基于Web的校园兼职信息发布与申请系统07059
前端·vue.js·spring boot·mysql·typescript·spark·课程设计
ynchyong10 天前
TS 基础
typescript·ts