【问题标题】:Type declaration for function with additional properties具有附加属性的函数的类型声明
【发布时间】:2022-01-17 13:58:47
【问题描述】:
【问题讨论】:
-
"TS 认为 foo 会返回函数,并且不能使用 payload 参数调用它自己" - 这正是你定义的,(): T 意味着它可以调用没有参数并返回T。试试tsplay.dev/mpvr7w。另请注意,您的游乐场链接已损坏。
标签:
typescript
typescript-typings
【解决方案1】:
你可以使用泛型:
TS Playground link
type FuncWithExtraProps<T> = T & {
<P>(payload: P): T & { payload: P };
}
declare const foo: FuncWithExtraProps<{ type: string }>;
foo.type
const result = foo({ name: 'john' });
您甚至可以限制参数的类型:
TS Playground link
type Fn<
Params extends unknown[] = any[],
Result = any,
> = (...params: Params) => Result;
type FuncWithExtraProps<ExtraProps, Payload> = (
Fn<
[payload: Payload],
ExtraProps & { payload: Payload }
>
& ExtraProps
);
declare const foo: FuncWithExtraProps<{ type: string }, { name: string }>;
foo.type
const result = foo({ name: 'john' });
【解决方案2】:
请查看related问题。
考虑这个例子:
type FuncWithType = {
(): (payload: { name: string }) => ({ type: string; payload: { name: string } });
type: string
}
const foo: FuncWithType = () => {
return (payload) => ({
type: 'foo',
payload
})
}
foo.type='hello'
Playground
请记住,您对FuncWithType 的表示需要返回一个函数的函数。
这个语法(): (payload: { name: string }) => ({ type: string; payload: { name: string } }); 意味着有一个没有参数() 的函数返回另一个带有payload 参数的函数。
如果你想声明一种非柯里化函数,你可以使用这个语法:
type FuncWithType =
& ((payload: { name: string }) => ({ type: string; payload: { name: string } }))
& {
type: string
}
const foo: FuncWithType = (payload) => ({
type: 'foo',
payload
})
foo.type = 'hello'