TypeScript:在接口定义中重用函数定义
TypeScript: Reuse function definitions in an interface definition
在下面的一段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
}
除了复制粘贴之外,我还没有找到重用该定义的方法。有没有比复制粘贴更好的方法?如果我必须先定义接口并将其成员作为静态导出重用,那也没关系。
baz
的类型可以通过类型计算重复使用(在本例中为 typeof
和 |
):
// Foo will contain 2 overloads of baz
type Foo = { (a: string): string; } | typeof baz;
但是请注意 type
与 interface
在某种程度上有所不同。例如它不能在 class .. implements ..
.
中使用
在下面的一段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
}
除了复制粘贴之外,我还没有找到重用该定义的方法。有没有比复制粘贴更好的方法?如果我必须先定义接口并将其成员作为静态导出重用,那也没关系。
baz
的类型可以通过类型计算重复使用(在本例中为 typeof
和 |
):
// Foo will contain 2 overloads of baz
type Foo = { (a: string): string; } | typeof baz;
但是请注意 type
与 interface
在某种程度上有所不同。例如它不能在 class .. implements ..
.