【发布时间】:2018-06-07 21:27:24
【问题描述】:
我想使用自定义类型定义来使 Express API 中的返回类型更加具体。我们使用app.set 和app.get 将全局对象保留在我们的应用程序中。
app.get('foo') 返回一个特定的类MyClass,所以我想用 TypeScript 来表达这个事实,以避免必须显式转换。
包含的index.d.ts 中app.get 的现有定义如下所示:
get: ((name: string) => any) & IRouterMatcher<this>;
在我的自定义类型定义中,我添加了以下内容:
import { MyClass } from '../MyClass';
declare global {
namespace Express {
export interface Application {
get (name: 'foo'): MyClass;
// also tried this to conform to existing structure:
// get: ((name: 'foo') => MyClass);
}
}
}
但是在这两种情况下,app.get('foo') 的返回类型仍然是any。
在执行以下操作时是否可以隐式具有正确的类型……:
let myObject = app.get('foo');
…为了避免不得不写:
let myObject: MyClass = app.get('foo');
【问题讨论】:
标签: typescript express interface