Lokomotywa
Lokomotywa

Reputation: 2844

compiling valid javascript as typescript leads to compile errors

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?

Upvotes: 0

Views: 24

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249636

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 = [];
}

Upvotes: 3

Related Questions