在 Typescript 中,如果接口和类具有相同的名称并且位于同一文件中,则可以合并它们:
interface Test {
example(input: 'a number'): number;
example(input: 'a string'): string;
}
class Test {
example(input: string): any {
//return something
}
}
const obj = new Test();
obj.example('a number'); //return type is number
obj.example('a string'); //return type is string
obj.example('something else'); //return type is any
Run Code Online (Sandbox Code Playgroud)
然而,似乎没有办法将这些接口定义拆分为多个文件,例如:
//test.interface.ts
export interface Test {
example(input: 'a number'): number;
example(input: 'a string'): string;
}
//test.class.ts
import "./test.interface.ts";
class Test {
example(input: string): any {
//return something
}
}
const obj = new Test();
obj.example('a number'); //return type is any but should be number
obj.example('a string'); //return type is any but should be string
obj.example('something else'); //return type is any
Run Code Online (Sandbox Code Playgroud)
将类和实际接口之间的接口定义拆分为多个文件的正确方法是什么?
此问题的解决方案是重新声明“托管”打字稿模块以扩充其定义:
//test.interface.ts
declare module './test.class.ts' {
interface Test {
example(input: 'a number'): number;
example(input: 'a string'): string;
}
}
//test.class.ts
import "./test.interface.ts";
class Test {
example(input: string): any {
//return something
}
}
const obj = new Test();
obj.example('a number'); //return type is number
obj.example('a string'); //return type is string
obj.example('something else'); //return type is any
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2597 次 |
| 最近记录: |