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 代码。这种技巧在处理配置对象、依赖注入和其他需要类型约束的场景中特别有用。

相关推荐
Flynt8 小时前
NestJS 12升级踩坑:从Webpack到Rspack,我折腾了一整个周末
typescript·node.js·nestjs
PBitW21 小时前
为什么vite中TS报错,可以继续运行?Webpack不行?
前端·webpack·typescript·vite
爱丶不疚1 天前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript
YHHLAI1 天前
TypeScript 高级工具类型面试指南
ubuntu·面试·typescript
shmily麻瓜小菜鸡1 天前
JavaScript / TypeScript 易踩坑知识点完全指南 -假值(Falsy Values)完全指南
开发语言·javascript·typescript
用户0934077735141 天前
HarmonyOS WPS Open SDK 实践:把水印与修订收成打开策略层
android·typescript·harmonyos
古夕1 天前
my-first-ai-web_学习记录05——NextAuth Adapter 存储用户信息
typescript·全栈·next.js
退休倒计时1 天前
【每日五题】leetcode TypeScript
算法·leetcode·职场和发展·typescript
我就是DaLing呀!1 天前
vue3 + 独立的数据管理 Store实现视频剪辑功能
前端·typescript·vue3·canvas·store
BillKu3 天前
TypeScript中,字符串字面量联合类型(Union Type)、enum的用法说明
前端·javascript·typescript