Possible to chain generics in Cypress custom command chains?

老子叫甜甜 提交于 2020-04-30 11:42:25

问题


I'm new to Typescript. Prior to switching js-> ts, I was doing a lot of

cy.request('GET', '/foo')
.its('body.bar')
// etc

Now, the its line will (understandably) give a typescript error, because that's sorta a compound String Literal Type, so keyof is insufficient.

My code currently looks sorta like this

export interface TypedResponse<BodyType extends BodyType> {
    body: BodyType
};

export interface BodyType {
    [key: string]: any
}

export interface FooBodyType extends BodyType {
    bar: number
}


cy.request('GET', '/foo') as Cypress.Chainable<TypedResponse<FooBodyType>>
.its('body')
.its('bar')
// etc

But I'd rather make my own overload (mostly because of how its impacts results formatting), something like:

Cypress.Commands.add('itsBody', {prevSubject: true}, 
    <T extends BodyType, K extends keyof T['body']>(subject: T, bodyPropertyName: K, options?: any):    Cypress.Chainable<T['body'][K]> => {
    // @ts-ignore
    return cy.wrap(subject).its(`body.${bodyPropertyName}`, options);
});

Problem is that due to the way that Cypress parameter shifts custom commands, my index.d.ts version doesn't have the subject parameter, and so there's no way to enforce that a user isn't going .itsBody('nonexistent')

I imagine there's probably a way around this, given how much Cypress relies on chaining... I just can't for the life of me figure out how to get T from the return type of the previous command in the chain. It could be that this sort of thing is possible in vanilla TypeScript, but not in Cypress?

来源:https://stackoverflow.com/questions/60184009/possible-to-chain-generics-in-cypress-custom-command-chains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!