【问题标题】:Typescript - nested, multiple type assertionTypescript - 嵌套的多类型断言
【发布时间】: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


    【解决方案1】:

    我不得不阅读一些关于泛型类型参数的资料,但最终还是可行的。

    为了弄清楚发生了什么,我使用了ts-node 并构建了相互扩展的小型接口,以及将它们用作通用参数的其他接口。

    最终我能够在我的测试中模拟 Request 对象;例如:

        const fn: (options: (request.CoreOptions & request.UriOptions), callback?: request.RequestCallback) => any =
            function(options: (request.CoreOptions & request.UriOptions), cb?: request.RequestCallback) {
                expect(options.uri).to.equal('http://foo/id-xyz');
                done();
                return <request.Request>{};
            };
    
        const fakeRequester = <request.RequestAPI<request.Request, request.CoreOptions, {}>>fn;
    
        const agent = _agent(fakeRequester);
    
        agent('http', '/foo/id-xyz', { 'Accept-Encoding': 'gzip' }, fakeWritable(), (err, result) => {});
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2019-08-21
      • 2021-12-29
      • 2020-10-30
      • 2018-11-19
      • 1970-01-01
      • 2020-02-15
      相关资源
      最近更新 更多