1

I wrote the following setter in TypeScript:

public set data(data: Array<Data>) {
  console.log(data[0].getterProperty);
  console.log(data[0] instanceof Data);
  console.log(typeof data[0]);
  this.setGridDataIfReady();
}

Assuming data contains one item, this prints

undefined
false
object

Why is this happening? Shouldn't just objects of type Data be in the array, if I specified it like that?

2
  • 1
    and what do you assign to the setter? This is the most important part and you don't provide it... In other words - what is the data you pass? Commented Jul 14, 2017 at 12:20
  • 1
    and what is Data? a class or interface or something else? Commented Jul 14, 2017 at 12:22

1 Answer 1

1

It is worth noting that Typescript is not a executable language, it transpiles into JavaScript. This means that at run-time you are running JavaScript and not Typescript. Because of this, sometimes you get weird behavior.

It is true that you set the type of your array to "Data", but when the Typescript is transpiled, the run-time type is just "Object". This isn't like Java where passing in an incorrect type will throw an Exception. Don't expect the Typescript types to prevent any run-time errors.

If you want to actually capture the type and fail if an array entry is not of type "Data", be sure that all entries were created using "new Data". This will set the constructor of the object and make "instanceof Data" return true.

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

1 Comment

But 'data[0] instanceof Data' should still return true, even in javascript! Unless the array is empty.

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.