Reputation: 4205
Let's create two dummy classes and some example code:
class A {
constructor() {}
}
class B extends A {
value: number;
constructor(value: number) {
super();
this.value = value;
}
}
const values: A[] = [new A(), new A(), new B(123)];
const oneOfThem = values[2];
validateB(oneOfThem);
console.log(oneOfThem.value);
function validateB(item: A): asserts item is B {
if (!(item instanceof B)) {
throw new Error('wrong type!');
}
}
This code runs perfectly.
The thing is I need to wrap validateB
with another function:
function validateBWrapper(item: A) {
return validateB(item);
}
But as soon as I use this function instead of validateB
in the code above, it loses the asserts ...
info:
I don't want to copy asserts item is B
to the wrapper function. In my actual usage, the wrapping function wraps a function it gets a parameter.
I'm trying to find something similar to ReturnType<>
, but with asserts
.
Is there any way to retrieve asserts
info from a given function?
Thanks!
Upvotes: 1
Views: 111
Reputation: 13574
Unfortunately, you are right, asserts
and is
are special keywords that help typescript parser to understand our goals when ReturnType<>
only extracts a type, in case of asserts
it is void
and in case of is
it is boolean
.
and without saying explicitly that function asserts
or value is T
there's no way to inherit it.
The way we have - to open an issue on github and to wait until they add a new utility type for it here https://www.typescriptlang.org/docs/handbook/utility-types.html
Upvotes: 1