Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript 2.0 method type guards?

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.

like image 964
jrbedard Avatar asked Oct 18 '22 01:10

jrbedard


1 Answers

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.

like image 113
Nitzan Tomer Avatar answered Oct 21 '22 03:10

Nitzan Tomer