TypeScript如何实现接收泛型类型并指定其泛型参数?
解决方案:用类型构造器实例化实现
ApplyWorld 我们可以利用TypeScript对泛型类型的实例化能力,直接将目标泛型类型构造器应用于'world'来得到结果,无需冗长的条件类型分支:
// 原类型定义 type MyType<T extends string = string> = { hello: T }; type WithFoo<T extends string = string> = { foo: 'bar' } & MyType<T>; type WithFizz<T extends string = string> = { fizz: 'buzz' } & MyType<T>; // 定义ApplyWorld:接受泛型类型构造器,返回其泛型参数为'world'的实例 type ApplyWorld<C extends <T extends string>() => unknown> = C<'world'>; // 测试用例 type FooWithWorld = ApplyWorld<typeof WithFoo>; // FooWithWorld 最终类型:{ foo: 'bar', hello: 'world' } type FizzWithWorld = ApplyWorld<typeof WithFizz>; // FizzWithWorld 最终类型:{ fizz: 'buzz', hello: 'world' }
原理说明
这里的核心是把WithFoo、WithFizz这类泛型类型看作类型构造器(即接受泛型参数并返回对应类型的“类型层面函数”)。通过typeof WithFoo获取到这个构造器的类型,然后直接传入'world'作为泛型参数,就能得到我们需要的最终类型。
这种方式避免了为每个子类型写条件分支,扩展性更好,尤其适合复杂架构中大量同结构泛型类型的场景。
如果需要更严格的约束(确保构造器返回的类型继承自MyType),可以添加额外的泛型约束:
type ApplyWorld<C extends <T extends string>() => MyType<T> & Record<string, unknown>> = C<'world'>;
这样可以确保传入的构造器返回的类型必须是MyType与其他属性的交叉类型,避免误用。
内容的提问来源于stack exchange,提问作者mstephen19
相关产品推荐
相关产品推荐

