【问题标题】:TypeScript: Reuse function definitions in an interface definitionTypeScript:在接口定义中重用函数定义
【发布时间】:2018-01-10 19:36:14
【问题描述】:

在下面的 TypeScript 定义代码中,我想为Foo 接口的baz 属性重用baz 的函数类型。

declare module 'foo' {

  /* Not all exports will be reused in the interface. */
  export function bar(a: string): string

  /* Imagine a big and verbose function
     definition with plenty overloadings: */
  export function baz(a: number): number
  export function baz(a: Overloaded): number

  interface Foo {

    /* The interface is for a function, so I cannot use module */
    (a: string): string

    /* how do I reuse the full definition of the baz function? */
    baz

  }

  export default Foo

}

除了复制粘贴之外,我还没有找到重用定义的方法。有没有比复制粘贴更好的方法?如果我必须先定义接口并将其成员重用为静态导出,那也没关系。

【问题讨论】:

    标签: typescript reusability


    【解决方案1】:

    baz 的类型可以在类型计算中重复使用(在本例中为typeof|):

    // Foo will contain 2 overloads of baz
    type Foo = { (a: string): string; } | typeof baz;
    

    但是请注意,typeinterface 有某种不同。例如不能用于class .. implements ..

    【讨论】:

    • 谢谢! typeof 就是答案。不过,回答我的特定问题应该是这样的:interface Foo = { (a: string): string; baz: typeof baz }.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2023-02-22
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2017-02-19
    相关资源
    最近更新 更多