我想解决如何做我认为会被称为'嵌套类型断言'。Typescript - 嵌套,多类型断言
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类型。通过要求一个内部接口的接口断言一个对象所需的语法
export interface RequestAPI<TRequest extends Request, TOptions extends CoreOptions, TUriUrlOptions> {
在此工作过,我发现的例子:
在声明文件,RequestAPI被定义
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>> {{}, {}, {}};
等。
如果有人知道如何处理嵌套,多个断言或能指出我在做什么错的,它会受到赞赏。