如何为含可选值与默认值的对象添加TypeScript类型?
TypeScript 保留默认值的函数重构方案
你遇到的问题核心是:TypeScript 接口仅负责类型约束,无法定义运行时默认值,因此需要把类型校验和默认值逻辑分开实现,下面提供两种可行方案:
方案一:解构参数中保留默认值 + 接口类型约束
这是最贴近原 JavaScript 写法的方案,直接在函数的参数解构里保留原默认值,同时用接口标注参数类型:
interface IPayload { guid: string; numItems: number; lastDate: string; filters: string[]; includeCart?: boolean; fetchStuff?: boolean; withLove?: boolean; } export default ({ guid, numItems, lastDate, filters = [], includeCart = true, fetchStuff = true, withLove = true }: IPayload) => () => { // do stuff };
- 接口里的可选属性(
?)对应原函数中带默认值的参数,明确告知 TypeScript 这些属性可以不传 - 函数解构时的默认值会在运行时生效,未传入的属性会使用默认值而非
undefined,完全保留原函数行为
方案二:集中管理默认值 + 参数合并
如果需要集中管理默认值(比如默认值需要在多个地方复用),可以定义一个默认值对象,再和传入的参数合并,同时通过类型工具确保必填参数必须传入:
// 定义完整的Payload类型,所有属性都为必填(因为合并后都会有值) interface IPayload { guid: string; numItems: number; lastDate: string; filters: string[]; includeCart: boolean; fetchStuff: boolean; withLove: boolean; } // 定义可选参数的默认值 const defaultPayload: Omit<IPayload, 'guid' | 'numItems' | 'lastDate'> = { filters: [], includeCart: true, fetchStuff: true, withLove: true }; // 使用Partial让可选属性变为可选,Pick强制必填参数必须传入 export default (payload: Partial<IPayload> & Pick<IPayload, 'guid' | 'numItems' | 'lastDate'>) => { // 合并默认值和传入参数,确保所有属性都有值 const mergedPayload = { ...defaultPayload, ...payload } as IPayload; return () => { // 这里直接使用mergedPayload,所有属性都有明确类型和值 // do stuff }; };
Omit用来排除必填属性,只定义可选属性的默认值Partial<IPayload> & Pick<IPayload, ...>确保调用函数时必须传入guid、numItems、lastDate,其余属性可选- 合并后的
mergedPayload会自动拥有所有属性的正确值和类型
内容的提问来源于stack exchange,提问作者noblerare
相关产品推荐
相关产品推荐

