For the purpose of this demonstration, let's define two dummy classes and include some example code:
class X {
constructor() {}
}
class Y extends X {
value: number;
constructor(value: number) {
super();
this.value = value;
}
}
const valuesList: X[] = [new X(), new X(), new Y(123)];
const chosenValue = valuesList[2];
validateY(chosenValue);
console.log(chosenValue.value);
function validateY(item: X): asserts item is Y {
if (!(item instanceof Y)) {
throw new Error('wrong type!');
}
}
The code above executes without any errors.
Now, the issue arises when a wrapper function needs to be introduced around validateY
:
function validateYWrapper(item: X) {
return validateY(item);
}
However, by using the wrapper function instead of validateY
in the previous code snippet, the asserts ...
information is lost:
https://i.sstatic.net/nNyKM.png
I am looking for a solution where I don't have to duplicate asserts item is Y
in the wrapper function. In my actual scenario, the wrapping function wraps another function that accepts a parameter.
I'm exploring options similar to ReturnType<>
, but specifically for asserts
.
Is there a way to extract asserts
information from a given function?
Thank you!