reza
reza

Reputation: 6358

What does the following syntax mean?

I see code such as

export interface SmartType {
    type: string;
    [x: string]: any;
}
    

can someone explain the what the last line, defining x means?

Upvotes: 2

Views: 166

Answers (3)

Sébastien
Sébastien

Reputation: 12139

Adding something that is not explicit in other answers. The following TypeScript interface:

interface SmartType {
    type: string;
    [x: string]: any;
}

Requires the presence of a 
key named type that only accepts values of type string.

Then it specifies that any other key may be strings and that they may hold any type of value. But those other keys could also be numeric.

And the only reason that type can hold strings is because the string type is a subset of the any type (the type of the indexer in the SmartType interface).

That's why, in addition to the required type property, you can add any number of properties holding any type of value in an object of type SmartType.

const someSmartValue: SmartType = {
    type: 'some text',
    whatever: {},
    anyOtherTextProperty: ['array', 'containing', 'whatever', 1000, true, {a: () => false}],
    2: () => 'OK'
};

Check it on TypeScript Playground

Changing the return value of the indexer to boolean would render the definition invalid:

interface InvalidType {
    type: string; // [ts] Property 'type' of type 'string' is not assignable to string index type 'boolean'.
    [index: string]: boolean;
}

With the SmartType interface, the following would also be illegal, because a key named type is specifically required:

const anotherSmartValue: SmartType = {
    someProp: {}
}; // [ts] Type '{ someProp: {}; }' is not assignable to type 'SmartType'. Property 'type' is missing in type '{ someProp: {}; }'.

Upvotes: 1

Corey Ogburn
Corey Ogburn

Reputation: 24769

This means that a SmartType can be indexed with strings and values are of type any.

interface SmartType {
    type: string;
    [x: string]: any;
}

let obj: SmartType = { type: 'Thing' };
obj['test'] = 'Hello World';
obj['test2'] = 10;
console.log(obj);

(jsFiddle)

The typescript handbook explains this in its section on Interfaces: Indexable Types.

Upvotes: 3

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3649

It doesn't define x, what it does is it says that objects of SmartType can be indexed into with a string index, and values stored in those indices are of type any:

const s: SmartType;
s['foo']; // -> any

x is just a name, that's there more to give the keys a meaning, I presume. Any other name wouldn't change the meaning of the line.

Upvotes: 2

Related Questions