TypeScript带泛型约束函数返回具体值而非类型的问题解决
TypeScript泛型函数返回值类型修正问题
现有如下TypeScript代码:
function createGenericCoordinates<Type extends number | string>(x: Type, y: Type) { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); // Error (TS2322) // Type 3 is not assignable to type 1 | 2 genericCoordinates.x = 3;
需求是修改该函数,使返回值的x和y类型为number或string(而非传入的具体字面量值,如示例中的1|2),同时保留输入参数x和y必须同为number或同为string的约束(不能让参数接受任意类型)。
解决方案
方案1:显式指定返回值类型
保留泛型约束以确保输入参数类型一致,同时直接指定返回值为基础类型number | string:
function createGenericCoordinates<Type extends number | string>(x: Type, y: Type): { x: number | string; y: number | string } { return { x, y }; } const genericCoordinates = createGenericCoordinates(1, 2); genericCoordinates.x = 3; // 不再报错 createGenericCoordinates(1, "test"); // 依然会报错,符合类型约束要求
方案2:使用函数重载
通过函数重载实现输入类型约束,同时让返回值自动推导为基础类型:
// 重载签名:约束输入为同类型的number或string function createGenericCoordinates(x: number, y: number): { x: number; y: number }; function createGenericCoordinates(x: string, y: string): { x: string; y: string }; // 实现签名:处理实际逻辑 function createGenericCoordinates(x: number | string, y: number | string) { return { x, y }; } const numCoords = createGenericCoordinates(1, 2); numCoords.x = 3; // 正常 const strCoords = createGenericCoordinates("a", "b"); strCoords.y = "c"; // 正常 createGenericCoordinates(1, "b"); // 报错,符合约束
方案3:泛型映射为基础类型
通过条件类型将泛型字面量类型映射为对应的基础类型:
function createGenericCoordinates<Type extends number | string>(x: Type, y: Type): { x: Type extends number ? number : string; y: Type extends number ? number : string; } { return { x, y }; } const coords = createGenericCoordinates(1, 2); coords.x = 5; // 正常
这三种方案都能满足需求:既限制输入参数必须同为number或string,又让返回值的属性类型为基础类型而非具体字面量值,可根据实际场景选择合适的方案。
内容的提问来源于stack exchange,提问作者makkabi
相关产品推荐
相关产品推荐

