如何在TypeScript赋值时根据键的类型推断变量类型?
解决方案:通过泛型推导实现赋值时的类型推断
你的代码问题出在泛型默认参数的使用上——当你省略泛型参数直接写const a: AB = ...时,T会被解析成默认的联合类型{ id: ONETWO },而这个联合类型无法单独匹配{ id: typeof ONE }或{ id: typeof TWO },最终返回never。
要在赋值阶段实现类型推断,你可以通过以下两种方式解决:
方式一:泛型辅助函数(推荐)
利用函数的泛型自动推导能力,让TypeScript根据传入的参数自动推断最终类型:
const ONE = '1'; const TWO = 2; type A = { id: typeof ONE }; type B = { id: typeof TWO }; type ONETWO = typeof ONE | typeof TWO; type AB<T extends { id: ONETWO }> = T extends { id: typeof ONE } ? A : T extends { id: typeof TWO } ? B : never; // 辅助函数,自动推导泛型T const createAB = <T extends { id: ONETWO }>(obj: T): AB<T> => obj as AB<T>; // 赋值时自动推断类型 const a = createAB({ id: ONE }); // typeof a 为 A const b = createAB({ id: TWO }); // typeof b 为 B
方式二:显式指定泛型参数
如果不想用辅助函数,可以在赋值时显式指定泛型的具体类型,让条件类型正确匹配:
const ONE = '1'; const TWO = 2; type A = { id: typeof ONE }; type B = { id: typeof TWO }; type ONETWO = typeof ONE | typeof TWO; type AB<T extends { id: ONETWO }> = T extends { id: typeof ONE } ? A : T extends { id: typeof TWO } ? B : never; // 显式指定泛型参数 const a: AB<{ id: typeof ONE }> = { id: ONE }; // 类型为A const b: AB<{ id: typeof TWO }> = { id: TWO }; // 类型为B
核心原理
TypeScript的条件类型需要明确的输入类型才能正确分支判断。当你使用默认泛型参数时,输入的是单一联合类型{ id: '1' | 2 },而非{ id: '1' } | { id: 2 },无法触发分布式条件类型的分支逻辑,导致返回never。通过显式指定泛型或利用函数推导传入具体的单一类型,就能让条件类型正确匹配,得到预期的A或B类型。
内容的提问来源于stack exchange,提问作者lahsuk
相关产品推荐
相关产品推荐

