Deepsy
Deepsy

Reputation: 3800

ImmutableJS Records won't detect interface with Typescript

I'm trying to get running Typescript with Immutable 3.8.1.

import { Record } from "immutable";

class Person extends Record({
    name: "viktor" as string,
}) {
    getName() {
        return this.name;
    }
}

const person = new Person({ name: "petko" });

console.log(person.getName());

this code produces the following error:

    Property 'name' does not exist on type 'Person'.
     5 | }) {
     6 |    getName() {
  >  7 |        return this.name;
       |                    ^^^^
     8 |    }
     9 | }

but it does compile and run. However, when I try to add name: string; just over the getName declaration (in the class body), the error goes away, but getName() returns undefined every time. What I'm doing wrong?

Upvotes: 0

Views: 174

Answers (1)

FZs
FZs

Reputation: 18619

I'm not that advanced in TS, but if I got it right, the problem is that although the property name does exist on type Person, the TypeScript compiler doesn't know about it, because it's created dynamically at runtime.

So, you have two ways:

  • Use the immutable record's get function to read the value:

      import { Record } from "immutable";
    
      class Person extends Record({
          name: "viktor" as string,
      }) {
          getName() {
              return this.get("name");
          }
      }
    
      const person = new Person({ name: "petko" });
    
      console.log(person.getName());
    
  • Cast to any:

      import { Record } from "immutable";
    
      class Person extends Record({
          name: "viktor" as string,
      }) {
          getName() {
              return (<any> this).name;
          }
      }
    
      const person = new Person({ name: "petko" });
    
      console.log(person.getName());
    

Upvotes: 1

Related Questions