[英]How to type a variant of a function with no optional arguments - with mapped tuple
I try to make a typing for a function that has the exact same arguments that the source function, but where none are optional.我尝试为具有与源函数完全相同的参数的函数打字,但没有一个是可选的。
I tried to use a mapped tuple, using the logic:我尝试使用映射元组,使用逻辑:
type IFArgs = ArgsN<typeof getFunc>
type IMappedIFArgs = {[N in keyof IFArgs]-?: IFArgs[N]} // The -? removes "optionality"
const getFuncMandatory = <(...args: IMappedIFArgs) => string>getFunc // Error: IMappedIFArgs not a tuple...
Where ArgsN comes from the tsargs
library, and is defined cleverly like this:其中 ArgsN 来自
tsargs
库,并巧妙地定义如下:
export type ArgsN<T extends (...args: any[]) => any> = T extends (...args: infer K) => any ? K : never;
According to the 3.1 documentation, the mapped type should also be a tuple, when the source is a tuple.根据 3.1 文档,当源是元组时,映射类型也应该是元组。 This seems to be almost the case, when inspecting in VS Code - but not close enough for the compiler to accept it as an argument.
在 VS Code 中进行检查时,情况似乎几乎如此 - 但还不够接近编译器将其作为参数接受。 Also, the length of the mapped type returns
2 | 3
此外,映射类型的长度返回
2 | 3
2 | 3
, not 3
- which makes sense, but is not what I want. 2 | 3
,而不是3
- 这是有道理的,但不是我想要的。
Any ideas how to make the mapped tuple a valid argument tuple?任何想法如何使映射的元组成为有效的参数元组? Any ideas on how to archive the same using other mechanisms would also be nice.
关于如何使用其他机制存档相同的任何想法也很好。
A few of the types you define already exist within TypeScript.您定义的一些类型已经存在于 TypeScript 中。
I haven't investigated the differences between what's going on here and what you have, but this seems to work:我还没有调查这里发生的事情和你所拥有的之间的区别,但这似乎有效:
function getFunc(n:number,s?:string):void{}
type IFArgs = Parameters<typeof getFunc>
type IMappedIFArgs = Required<IFArgs>
const getFuncMandatory = getFunc as ((...args: IMappedIFArgs) => string)
See the definitions of these types to compare to your own implementation: Parameters
, Required
查看这些类型的定义以与您自己的实现进行比较:
Parameters
, Required
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.