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

相关推荐
水獭比特10 小时前
Agent 的 timeout 为什么会失效?把一条总预算传到底
人工智能·typescript
xcLeigh10 小时前
编程语言的 AI 友好度排名:Python、JavaScript、TypeScript 谁更适合 AI 辅助
javascript·人工智能·python·ai·typescript·ai编程
谷哥的小弟10 小时前
TypeScript中的any
javascript·typescript
谷哥的小弟11 小时前
TypeScript在Vue3中的常见写法
前端·javascript·typescript
njsgcs11 小时前
链轮 平键和键槽的标准尺寸 计算 typescript
typescript·机械工程
满栀58515 小时前
请求拦截、响应拦截、业务错误统一处理
前端·typescript·anti-design-vue
谷哥的小弟18 小时前
TypeScript接口
javascript·typescript
谷哥的小弟20 小时前
TypeScript类型断言
前端·javascript·typescript
子兮曰2 天前
Elysia vs Hono 完整性能对比:Bun 专属优化还是跨平台通用,2026 实测数据给出的答案
前端·后端·typescript
To_OC2 天前
从一个颜色选择器说起:我终于整明白了 React+TS 里的 model 与 api 分层
前端·react.js·typescript