1

I create a type alias as follow

export type Nullable<T> = T | null | undefined;

I would like to have an extension method hasValue to check whether or not the instance is null or undefined. I tried to use prototype as

Nullable.prototype.hasValue = function(): boolean => {
    return Nullable<T>(this) === null || Nullable<T>(this) === undefined
}

However I get the following error.

'Nullable' only refers to a type, but is being used as a value here.

Can anyone please help? Thank you.

Ben
  • 957
  • 1
  • 11
  • 37
  • `type` definitions don't emit code in TypeScript. They are used for type checking only. If you want to define `hasValue`, either define `Nullable` as a `class` (i.e. container for some value) so you can define `hasValue` as a method, or define `hasValue` as a function accepting `Nullable`. – miqh Jan 12 '21 at 22:47
  • Hi @miqh, thank you for your suggestion. Happy to accept it as an answer if you would like to convert your comment to an answer. – Ben Jan 14 '21 at 12:24

1 Answers1

1

Here's the suggestions from my comment as an answer:

That compiler error you're seeing is trying to point out that type definitions don't generate any code and are only used for type checking.

To define a hasValue method that can be invoked on Nullable instances, you'll have to define Nullable as a class. Something to be mindful of with this option is it will incur a bit of overhead (i.e. having to create instances which wrap values).

A rudimentary example:

class Nullable<T> {
    value: T;
    constructor(value: T) {
        this.value = value;
    }
    hasValue() {
        return this.value != null;
    }
    /* ... */
}

Alternatively, you could define hasValue as a free function instead, which accepts a Nullable parameter.

miqh
  • 3,624
  • 2
  • 28
  • 38