alphanumeric
alphanumeric

Reputation: 19329

A Typescript syntax clarification

I am reading a code written in Typescript. I'm not sure if I understand it correctly:

export class MyClass<B> {
  value: B;

  constructor(value: B) {
    this.value = value;
  }

  isMyClass(): this is MyClass<B> {
    return true;
  }
}

  1. What does the <B> stand for? What does it represent, a Type? If so, what Type is it?

  2. What is this is MyClass<B> in isMyClass(): this is MyClass<B>? Is it being evaluated for true or false? Why not to put this inside of the function itself then, something like this:

  isMyClass() {
    if (this is MyClass) {
      return true;
    }
    else {
      return false;
    }    
  }

And I am not able to find the answer to a these questions.

Upvotes: 2

Views: 63

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

What does the <B> stand for? What does it represent, a Type? If so, what Type is it?

That's a type parameter, also known as generics. See the TS handbook.

In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is generics, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

Whenever one calls a function or creates an instance, if the function or class is generic, you can "pass" a type parameter to it, similar to how arguments can be passed to a function or constructor. (The difference is that the type parameter, being a type, doesn't exist in the emitted JS - it's just there to help TS type-check).

If so, what Type is it?

It's whatever type the constructor parameter is called with.

const m = new MyClass(3);

will result in

constructor(value: B)

where value is 3, telling TypeScript that the resulting instance is a MyClass<number> - in other words, that its value property holds a number, a B.

What is this is MyClass<B> in isMyClass(): this is MyClass<B>? Is it being evaluated for true or false? Why not to put this inside of the function itself then, something like this:

The

isMyClass(): this is MyClass<B> {

is a type guard. If the method returns true, it tells TypeScript that the instance is of type MyClass<B>.

While you could do something like:

  isMyClass() {
    if (this instanceof MyClass) {
      return true;
    }
    else {
      return false;
    }    
  }

That wouldn't allow TypeScript to understand that the type has been narrowed when isMyClass is called; it'll just return a boolean. In contrast, using the is will both return a Boolean and give TypeScript type information about what was called.

Upvotes: 4

Related Questions