TypeScript条件类型问题:getShape函数返回类型未正确包含undefined
getShape函数返回类型不匹配问题修复
问题
调用getShape时,返回类型未正确反映实际值的可能性:Object[varName]可能为undefined,但当前传入circle时类型仅显示Circle,传入square时仅显示Square,没有包含undefined。
现有代码
类型定义
export type TShape = 'circle' | 'square' export type TShapes<T> = T extends "circle" ? Circle | undefined : T extends "square" ? Square | undefined : never;
函数定义
protected static getShape<T extends TShape>(varName: T): TShapes<T> | undefined { return Object[varName] }
问题根源与修复
你在TShapes<T>的条件类型里已经为每种形状都定义了| undefined,但函数返回类型又额外叠加了| undefined,这会让TypeScript的类型推导出现错误,导致原本的undefined被忽略,只显示基础的Circle或Square类型。
只需要移除函数返回类型中多余的| undefined即可:
protected static getShape<T extends TShape>(varName: T): TShapes<T> { return Object[varName] }
修改后,当传入circle时,返回类型会正确显示为Circle | undefined;传入square时显示为Square | undefined,完全匹配实际值的可能情况。
另外注意:这里的Object应该是你存储形状实例的自定义对象(比如const shapes = { circle: new Circle(), ... }),如果误用了全局Object对象,Object[varName]始终会返回undefined,这部分逻辑需要确认正确。
内容的提问来源于stack exchange,提问作者1011 1110
相关产品推荐
相关产品推荐

