Friday, December 4, 2015

TypeScript 1.6–Interface errors

This week, a colleague asked me to have a look at his code. He was working on a web project with some TypeScript code but the moment he opened the project hundreds of errors appeared. We discovered that he recently upgraded to TypeScript 1.6 and in this version the object checking rules became more strict:

Before TypeScript 1.6 you could do something like this:

Note that although the interface only defines 3 properties, the compiler doesn’t complain when I add an extra property to my object literal.

In TypeScript 1.6 this is no longer the case, and an error is thrown when you add a property that is not part of the interface:

image

image

You can suppress this error by passing the --suppressExcessPropertyErrors compiler option.

Although I understand the reasoning behind this change, I’m not a fan of this behavior, as it breaks the dynamic nature of JavaScript.

More information in the following GitHub issue: https://github.com/Microsoft/TypeScript/issues/3755

1 comment:

Stephen Chung said...

I believe adding an indexer works? Such as:

interface Person {
firstName: string;
lastName: string;
kids: number;
[name:string]:any;
}

That would allow you to add any number of additional fields.