TypeScript:通过推断函数的参数类型来定义类型
TypeScript: Define a type by inferring a Function's Argument Types
是否可以描述由函数参数推断出的类型?我需要这样的东西:
// 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
};
我无法控制函数参数的签名,因此无法将其转换为 someFn(args: SomeFnArgs)
和 MyType<SomeFnArgs>
。
我不知道是否可以描述类型。
是的,虽然不完全是那样。键入函数签名时,参数名称会丢失。您的示例中 someFn
的参数类型是 [string, number?, any]
(尽管该示例不太有效,因为非可选参数可能不会出现在可选参数之后。
你可以用这个 (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
是否可以描述由函数参数推断出的类型?我需要这样的东西:
// 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
};
我无法控制函数参数的签名,因此无法将其转换为 someFn(args: SomeFnArgs)
和 MyType<SomeFnArgs>
。
我不知道是否可以描述类型。
是的,虽然不完全是那样。键入函数签名时,参数名称会丢失。您的示例中 someFn
的参数类型是 [string, number?, any]
(尽管该示例不太有效,因为非可选参数可能不会出现在可选参数之后。
你可以用这个 (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