【发布时间】:2018-03-08 15:24:33
【问题描述】:
我正在尝试研究如何执行我认为称为“嵌套类型断言”的操作。
Typescript 将允许您通过接口断言一个空对象以作为接口的类型。例如:
const fakeRequest = <ExpressCore.Request>{ protocol: 'test-protocol' };
让我指定一个具有协议字段集的对象,该对象集充当 ExpressCore.Request 类型(具有许多属性-https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/index.d.ts#L177)。我可以方便地使用它来获取一个 Request 对象并对协议进行断言。
当我尝试使用更复杂的接口执行此操作时,例如,为请求提供的接口 - https://github.com/request/request - 编译器告诉我必须提供三种内部类型:
Generictype 'RequestAPI<TRequest, TOptions, TUriUrl> requires 3 type argument(s).
我正在使用通过definitelyTyped 提供的@types/request 类型来执行此操作。
在声明文件中,RequestAPI定义为:
export interface RequestAPI<TRequest extends Request,
TOptions extends CoreOptions,
TUriUrlOptions> {
在研究这个问题后,我发现了通过需要一个内部接口的接口断言对象所需的语法示例:
const pos = <GeoJSON.Feature<GeoJSON.GeometryObject>>{
"type": "Feature",
"properties":{},
"geometry": {
"type": "Point",
"coordinates": [0, 1]
}
};
见What means "Generic type 'Feature<T>' requires 1 type argument(s)" in Typescript?。
但是,我无法弄清楚如何使用三个内部接口来做到这一点。以下尝试均失败:
const foo = { {} as request.Request, {} as request.CoreOptions, {} as request.RequiredUriUrl } as request.RequestAPI;
const fakeRequester = <request.RequestAPI<request.Request><request.CoreOptions><request.RequiredUriUrl>> {{}, {}, {}};
等等。
如果有人知道如何处理嵌套的多重断言或能指出我做错了什么,将不胜感激。
【问题讨论】:
标签: typescript2.0 definitelytyped