In TypeScript 2.0, why can I have a function type guard:
function hasValue<T>(value: T | undefined): value is T { return value !== undefined; }
But not a method type guard?:
export class Maybe<T> {
constructor(public value: T | undefined) {}
hasValue(): this.value is T { return this.value !== undefined; }
}
error on hasValue()
:
'{' or ';' expected.
There are a few issues here:
1) When using this
when declaring the return type then it's used as polymorphic this type and not as a reference to the instance of the class.
2) The docs on this matter clearly state that:
A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature.
If you use this.parameterName
then it isn't "a parameter from the current function signature".
You could argue that they could add it but then:
3) Type guards are functions which check a type and not a variable.
As the type itself isn't a part of the class then it makes sense that the type guard function won't be a part of the class as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With