0

Renaming my javascript files in .ts files and compiling them seems to be not as easy as assumed. I get a lot of type errors, which disturbs me since I expected type script to be a superset of javascript.

Simple example:

 var initial = { alive: [], destroyed: [] };
        if (modificationHelper.aliveCompare) {
            initial.aliveValues = [];
        }

Property 'aliveValues' does not exist on type '{ alive: any[]; destroyed: any[]; }

What is the cause, what can I do?

1
  • 1
    TypeScript's syntax is a superset of JavaScript, but not all JavaScript programs are correct TypeScript programs. Commented Feb 5, 2018 at 15:02

1 Answer 1

3

Typescript will validate that your code is type safe. While semantic errors (about type compatibility or missing properties, etc) do not block the compiler from emitting the javascript it is generally not a good idea to ignore them.

You will need to invest time in removing these errors. In this case Typescript does not allow the use of a property that is not known to be on the object. The type of the object is inferred when the first assignment happens, so you could try this:

var initial = { alive: [], destroyed: [], aliveValues : undefined as any[] };
if (modificationHelper.aliveCompare) {
    initial.aliveValues = [];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Note that if using a property that is not known to be on the object is in the intended behavior (e.g. if you're using an object as a dictionary), you can represent this in TypeScript using index signatures.
@JoeClay Yes, that is true, but in this case that does not seem to be the intended usage, it's just an object that has one property controlled by a flag.
Yeah, probably not the case here :)

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.