1

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);
    }
  }
}
3
  • Please include all relevant code in this question, not off-site. It makes the question self-contained, so it will have value even without the link Commented Mar 25, 2020 at 22:06
  • Wait, why do you think d.trans has that method? The value is d.trans=JSON.parse('{"val":"fil.SalesOrderNo=.slice(0,7)","note":""}'), so it wouldn't have any methods at all. Commented Mar 25, 2020 at 22:07
  • 1
    From the error message, it looks like d.trans isn't actually an instance of Transform. Look at the code where that object is generated. Commented Mar 25, 2020 at 22:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Doesn't make sense even as type casting, as that would still rely on objects being compatible. You can't do dog = new Dog() then later cast it as cat = <Cat> dog; and expect to be able to call cat.meow() without errors.
Yea that is true
Sorry, Im still confused.... the type may be object but since it EXACTLY matches a Transform, why is casting to a Transform object problem?
It is a compile-time cast/assertion not a runtime cast/assertion
@AdamWolski so that means the 'as Transform' would enable autocomplete at the UI level, but not necessarily make certain the object is of type Transform at runtime, which is what the error is about?

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.