【问题标题】:Type declaration for function with additional properties具有附加属性的函数的类型声明
【发布时间】:2022-01-17 13:58:47
【问题描述】:

任何人都知道如何为具有附加属性的函数定义类型,例如

foo({ name: 'john' })
foo.type

我假设以下方法可行,但 TS 认为 foo 会返回该函数,并且不能使用有效负载参数调用自身。

type FuncWithType = {
  (): (payload: { name: string}) => ({ type: string; payload: { name: string }});
  type: string
}

上面的例子和我的错误解决方案https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgrgOwMYHUCWwAWAVc0C8UA3gFBRQAUAlAFyVgC[…]QgSJFYEUSgGOnhkdCxcSAUoAAZ3BgpScj5BOgByYAhRItcqbIA6RyA(已编辑)

【问题讨论】:

  • "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 }) =&gt; ({ 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 2018-09-06
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多