假设我有一个函数类型,例如
type somefntype = (a: number, b: string, c: boolean) => void
我需要那个函数类型最后一个参数的类型:
type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean
如何定义LastParameter
?
最佳答案
更新:引入了 TypeScript 4.0 variadic tuple types ,这意味着 Last
现在可以简单地实现为
type Last<T extends any[]> = T extends [...infer I, infer L] ? L : never;
其余正常工作:
type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean
引入 TypeScript 3.0 tuple types in rest and spread expressions ,特别是允许函数参数列表类型和 tuples 之间的编程转换.有一个名为 Parameters<F>
的类型别名defined in the standard library以元组形式返回函数的参数列表。
这很烦人,但可以获取具有固定但任意长度的元组类型的最后一个元素:
// Tail<T> returns a tuple with the first element removed
// so Tail<[1, 2, 3]> is [2, 3]
// (works by using rest tuples)
type Tail<T extends any[]> =
((...t: T)=>void) extends ((h: any, ...r: infer R)=>void) ? R : never;
// Last<T> returns the last element of the tuple
// (works by finding the one property key in T which is not in Tail<T>)
type Last<T extends any[]> = T[Exclude<keyof T, keyof Tail<T>>];
把它们放在一起
type LastParameter<F extends (...args: any)=>any> = Last<Parameters<F>>;
我们可以测试它:
type somefntype = (a: number, b: string, c: boolean) => void
type lastparamtype = LastParameter<somefntype> // boolean
我觉得不错。 Link to code
关于 typescript :获取函数类型的最后一个参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56368755/