Rilcon42
Rilcon42

Reputation: 9765

Typescript cannot call function inside class by instance

Can someone explain why this is wrong? splitval is most definitely a function. I created a stackblitz with the code here- check console for error

function call:

[(this.filcol, this.strtrans)] = (d.trans as Transform).splitval();

Output:

edit trans:{"val":"fil.SalesOrderNo=.slice(0,7)","note":""} TypeError: d.trans.splitval is not a function

Class:

export class Transform {
  val: string;
  note: string;

  splitval(): [string, string] {
    try {
      let filcol = this.val.substr(0, this.val.indexOf("="));
      let strtrans = this.val.substr(this.val.indexOf("=") + 1);
      return [filcol, strtrans];
    } catch (e) {
      console.log("err shared model splitval:" + e);
    }
  }
}

Upvotes: 1

Views: 1258

Answers (1)

Adam Wolski
Adam Wolski

Reputation: 5656

You incorrectly use as operator. In TypeScript it means assertion. It is not going to convert an object to an instance of the class.

When you parse a JSON in the following line, as a result, you get a regular js object:

d.trans=JSON.parse('{"val":"fil.SalesOrderNo=.slice(0,7)","note":""}')

(d.trans as Transform) means to typescript that you are asserting that d.trans is an instance of Class Transform which is wrong because it is not.

Please consider the fixed code: angular-7qxpyu

Upvotes: 1

Related Questions