1

I started using tslint on my TypeScript project. When i reviewed the linted source, i noticed that sometimes keys were removed from objects.

I made a production build (locally) and no errors were shown. How is this possible? I could not find something about this behaviour on the net.

Before:

this.streamsDataModelDistance = new SimpleStreamsDataModel({
            polylineValueModels: polylineValueModels,
            fields: this.settingsModel.fields,
            commuters: distanceCommuters
        });

After:

this.streamsDataModelDistance = new SimpleStreamsDataModel({
            polylineValueModels,
            fields: this.settingsModel.fields,
            commuters: distanceCommuters
        });

Notice the missing key "polylineValueModels".

How does this even compile to JavaScript without errors? I'm hesitant to check this in into the trunk.

  • 2
    Possible duplicate of [Javascript object literal: what exactly is {a, b, c}?](https://stackoverflow.com/questions/34414766/javascript-object-literal-what-exactly-is-a-b-c) – Quentin Oct 30 '19 at 11:18
  • See also: https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript – Quentin Oct 30 '19 at 11:18
  • Why is TSLint doing any changes at all? It should just be telling you about what changes you need to make. As an aside, this is shorthand syntax `obj = { id }` is the same as `obj = { id: id }` – VLAZ Oct 30 '19 at 11:18
  • @VLAZ — TSLint has an option for automatic code formatting. – Quentin Oct 30 '19 at 11:19
  • @Quentin I wouldn't have thought this falls under the formatting functionality. All linters I've used consider stuff like whitespace to be auto-fixable, not any structural changes to the code. Sure, this *is* equivalent but it's more of a change than cosmetics. – VLAZ Oct 30 '19 at 11:20
  • @VLAZ — OK, it's called "fix" not "format". – Quentin Oct 30 '19 at 11:27

2 Answers2

3

You just enabled the object-literal-shorthand rule, you can set it in the tslint.json file.

{
 "rules": {
    "object-literal-shorthand": false
  }
}

https://palantir.github.io/tslint/rules/object-literal-shorthand/

This is not an error, it is the standard syntax of ECMAScript 2015.

In ECMAScript 2015, a shorthand notation is available, so that the keyword "function" is no longer necessary.

// Shorthand property names (ES2015)
var a = 'foo', b = 42, c = {};
var o = {a, b, c};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

Hsuan Lee
  • 2,095
  • 1
  • 8
  • 17
-1

This is fine and a handy shorthand.

TypeScript allows for easy assignment of object properties if the property has the same name as the variable.

const foo = "bar";
const object =  {
   foo
}

Will create an object containing of:

{
    foo: "bar"
}
k0pernikus
  • 41,137
  • 49
  • 170
  • 286