0

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?

1
  • 1
    "produces the following error but it does compile and run" - how does that fit together? Commented Nov 11, 2020 at 20:51

1 Answer 1

1

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());
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.