简体   繁体   English

TypeScript:通过推断函数的参数类型来定义类型

[英]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.

相关问题 typescript class 构造函数根据其 function 作为参数推断类型 - typescript class constructor inferring types based on args of its function as argument 传递内联函数调用时,TypeScript 不推断函数参数类型 - TypeScript not inferring function argument type when passing inline function call 如何根据Typescript中的字符串参数定义函数的参数类型? - How to define a function's argument type dependent on string argument in Typescript? TypeScript 包装函数推断类型 - TypeScript Wrapper Function Inferring Types 在 TypeScript 中推断 function 参数的参数 - Inferring the parameters of a function argument in TypeScript 推断 TypeScript 中的通用 function 类型 - Inferring generic function type in TypeScript 使用打字稿中类型对象的键推断类型 - Inferring types with a key of a type object in typescript 从在 Typescript 中抛出 function 的错误推断类型? - inferring types from an Error throwing function in Typescript? Typescript 从 function 条记录推断参数类型 - Typescript Inferring parameter types from function records Typescript: function 有 n 个联合类型 T 的参数,当调用者必须匹配类型时,为什么推断一个参数的类型不能推断全部? - Typescript: function with n parameters of union type T, why does inferring one param's type not infer all, when callers must match types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM