如何从TypeScript接口的可选函数中提取指定参数类型?
提取可选函数参数类型的TypeScript解决方案
给定以下TypeScript接口:
export interface Props { requiredProp: string; optionalFunction?: ( name: string, kind: 'animal' | 'human' ) => void; }
需要提取optionalFunction中kind参数的类型时,直接使用Parameters<Props['optionalFunction']>会报错——因为optionalFunction是可选属性,其类型包含undefined,而Parameters工具类型要求输入必须是纯函数类型。
可以通过两种方式解决:
方法一:用NonNullable排除undefined类型
先通过NonNullable剔除Props['optionalFunction']中的undefined,得到纯函数类型后再使用Parameters:
type Kind = Parameters<NonNullable<Props['optionalFunction']>>[1]; // Kind 的类型为 'animal' | 'human'
方法二:使用条件类型结合infer推断
利用条件类型判断目标属性是否为函数类型,同时推断参数数组:
type Kind = Props['optionalFunction'] extends (...args: infer Args) => void ? Args[1] : never; // Kind 的类型同样为 'animal' | 'human'
内容的提问来源于stack exchange,提问作者user9314872
相关产品推荐
相关产品推荐

