Closed HamedFathi closed 2 years ago
There was a bug in our docs, that the snippet didn't got rendered. Thats what you need to use:
// global.d.ts
declare global {
namespace PlaywrightTest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
We'll fix it soonish. Please also mark the stackoverflow answer as an answer.
How to specify the type of receiver argument while declaring a custom matcher?
Consider the declaration:
// global.d.ts
declare global {
namespace PlaywrightTest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
This matcher can be used as:
expect(1). toBeWithinRange(0,5);
// How to make it type safe so that we can't pass string inside expect:
expect("hello world"). toBeWithinRange(0,5);
@altamashali92 Late to the party but I have a working (if janky) solution:
declare global {
namespace PlaywrightTest {
const r: unique symbol;
const t: unique symbol;
interface Matchers<R, T> {
[r]: R;
[t]: T;
toBeWithinRange(this: Matchers<unknown, number>, a: number, b: number): R;
}
}
}
the funny unique symbols are needed otherwise the typecheck doesn't fail, because TS is structurally typed meaning that if R
/T
is never used in a property in Matchers
, then there is no difference between a Matchers<R, T>
and a Matchers<R, U>
@mxschmitt it looks like the docs are again missing (again due to some kind of formatting error?) from the new page?
In here you are explaining how to write a custom matcher
but in the last line, you have mentioned:
Could you please help me to find out how to write a Typescript compatible code in
global.d.ts
?I asked this in stackoverflow first but based on the answer maybe there is a problem.