1

I have a very simple class

export class Foo {

    name: string;

    index: number;

    toFullString(): string {
        return `${this.name} | ${this.index}`;
    }
}

And this is my ngFor:

<div *ngFor="let foo of foos">
    {{foo.toFullString()}};
</div>

And what I get is that method does not exist in the console:

self.context.$implicit.toFullString is not a function

I cannot figure out what's wrong in here. foo.name works fine and outputs all the elements. I suppose that the way typescript adds methods to an object messed up this for angular 2, but cannot figure out what to do.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • What do you iterate? Where are your 'foos' (plural) defined? – Meir Nov 09 '16 at 15:46
  • Now that you've asked I got what the problem was I think. I do create this object as a cast from the web server. Then they obviously fine for typescript, but this is not the real "class". This thing got me many times already :( The type safety for Typescript is a joke sometimes. – Ilya Chernomordik Nov 09 '16 at 15:50

1 Answers1

4

My guess is that you are not newing up the class, but doing a cast or conversion.

You need to do a new Foo(nameParam, indexParam) with an associated constructor taking the name and index constructor(public name, public index) { this.name = name; this.index = index; }

silentsod
  • 8,165
  • 42
  • 40
  • Yeah, I already got that :) Aking a new question if it can be made better in here: http://stackoverflow.com/questions/40511093/how-to-get-the-proper-class-during-a-cast-from-json-in-typescript – Ilya Chernomordik Nov 09 '16 at 15:57
  • I guess I won't delete the question just for the sake of someone else having troubles with typescript type safety and accept your answer. – Ilya Chernomordik Nov 09 '16 at 15:58
  • 1
    This has nothing to do with TypeScript's "type safety", this is the sole problem of JavaScript not having a type system. – Maximilian Riegler Nov 09 '16 at 16:01