[英]TypeScript: Define a type by inferring a Function's Argument Types
Is there any possibility to describe a type that gets inferred by a function's parameters?是否有可能描述由函数参数推断的类型? I need something like this:
我需要这样的东西:
// some fn I have no control over its params
function someFn(a: string, b?: number, c?: any): any { /* ... */ }
// my wanted type that describes the args as object-records:
const result: MyType<typeof someFn> = {
a: 'str',
b: 42,
c: null
};
I have no control over the signature of the functions' parameters, so converting it into someFn(args: SomeFnArgs)
and MyType<SomeFnArgs>
is not an option.我无法控制函数参数的签名,因此
someFn(args: SomeFnArgs)
将其转换为someFn(args: SomeFnArgs)
和MyType<SomeFnArgs>
。
I don't know if it is even possible to describe the type.我不知道是否可以描述类型。
Yes, although not quite in that way.是的,虽然不是那样。 The names of parameters are lost when typing function signatures.
键入函数签名时,参数名称会丢失。 The arguments type for
someFn
in your example is [string, number?, any]
(although that example is not quite valid, since non-optional parameters may not appear after optional parameters.您的示例中
someFn
的参数类型是[string, number?, any]
(尽管该示例不太有效,因为非可选参数可能不会出现在可选参数之后。
You can get this type with this ( playground ):你可以用这个( playground )获得这种类型:
// type Parameters<T extends Function> = T extends (...args: infer R) => any ? R : never;
// How it's implemented, Parameters is a built-in type.
function someFn(a: string, b?: number, c?: any): any { /* ... */ }
type T0 = Parameters<typeof someFn>; // type T0 = [string, (number | undefined)?, any?]
const x: T0 = ['hello', 42]; // good
const y: T0 = ['hello', 'world', '!!']; // bad
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.