Created
July 28, 2016 11:00
-
-
Save bennadel/38f103c74b83f54faa7e0c3d06a40c64 to your computer and use it in GitHub Desktop.
Object Access: Bracket-Notation vs. Dot-Notation With TypeScript In Angular 2 RC 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the core angular services. | |
import { Component } from "@angular/core"; | |
// Here, we're defining an object interface to contain a collection of values. This | |
// is nothing out of the ordinary and is, in fact, how we think about objects. According | |
// to the interface, however, the keys have to be strings. | |
// -- | |
// NOTE: In TypeScript, object interfaces must be defined as having "string" or | |
// "number" keys. | |
interface IData { | |
[ key: string ]: any; | |
} | |
@Component({ | |
selector: "my-app", | |
template: | |
` | |
<p> | |
<em>Check the console-logging</em>! | |
</p> | |
` | |
}) | |
export class AppComponent { | |
private data: IData; | |
// I initialize the component. | |
constructor() { | |
// Populate our arbitrary collection of data. | |
this.data = { | |
foo: "bar", | |
hello: "world" | |
}; | |
// Now, let's try to access the data that we just populated. In the first | |
// approach, we going to use bracket-notation (which clearly uses a string-key). | |
console.log( "[FOO]:", this.data[ "foo" ] ); | |
// Next, let's try to access the data using dot-notation. This approach should | |
// be "functionally equivalent" as the previous approach. | |
// -- | |
// CAUTION: While this is perfectly valid "JavaScript", TypeScript doesn't | |
// realize that "hello" is a "string" and raises a validation error. | |
console.log( "[HELLO]:", this.data.hello ); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IData { | |
[ key: string ]: any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment