Terse syntax for type definition on object literals?

Topics: General
Jun 16, 2014 at 9:36 PM
At the moment I need to do something like this.
export var Routes: {
        ControllerPattern: string;
        ActionPattern: string;
        IdPattern: string;
        QueryPattern: string
    } = {
        ControllerPattern: "{controller}",
        ActionPattern: "{action}",
        IdPattern: "{id}",
        QueryPattern: "{query}"
It can get quite tedious so I thought that having something like the following code would be nice.
export var Routes = {
    ControllerPattern: string = "{controller}",
    ActionPattern: string = "{action}",
    IdPattern: string = "{id}",
    QueryPattern: string = "{query}"
I'm not sure whether it makes sense but it's a lot less verbose and clear.

P.S. I'm pretty new to TypeScript so if there's something similar I'd be glad to know. :)
Jun 16, 2014 at 10:23 PM
The type of the variable is inferred from its initializer, so you can simply write:
export var Routes = {
    ControllerPattern = "{controller}",
    ActionPattern = "{action}",
    IdPattern = "{id}",
    QueryPattern = "{query}"
Marked as answer by EyalShilony on 6/16/2014 at 4:36 PM
Jun 16, 2014 at 10:46 PM
Yeah I did that exactly but then TSLint suggested to add explicit typedef, that's the reason I thought about it. :)
Jun 16, 2014 at 10:49 PM
I don't think that's a good rule to have. TypeScript is designed around the fact that types can be inferred in most places; making you add a type annotation to a literal is just making you write the same thing twice (most of the time).
Marked as answer by EyalShilony on 6/16/2014 at 4:36 PM
Jun 16, 2014 at 10:57 PM
Yeah, true, so would you say it's something that should be fixed within TSLint?