Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Property access for string index signatures #12671

Merged
merged 4 commits into from
Jan 18, 2017

Conversation

sandersn
Copy link
Member

@sandersn sandersn commented Dec 5, 2016

Fixes #12596

This PR allows property access (dotted syntax) for arbitrary identifiers on types that have an explicitly declared string index signature. Previously, only element access (bracket syntax) was allowed. For example:

interface Flags { [name: string]: boolean }
let flags: Flags;
// new
flags.thisIsFine = true;
flags.imOkayWithTheEventsThatAreUnfoldingCurrently = true;
// still works
flags["That's okay, things are going to be okay."] = true;

Improvements:

  1. Javascript says that property and element access are basically the same thing. Typescript does too now.
  2. Property access now behaves the way Javascript programmers expect. Less friction when learning Typescript and less code that needs to be rewritten to use element access.

Drawbacks:

Types with string index signatures allow any property name. This means:

  1. You won't get errors if you use a property that doesn't exist.
  2. The compiler won't report errors for typos.
interface Map<T> { [s: string]: T }
let forgot: Map<number>;
// oops, forgot isn't an array!
for (let i = 0; i < forgot.length; i++) {
  console.log(forgot[i]);
}

let cantType: Map<string>;
cantType.something = 'soemthing';
if (cantType.soemthing) {
  console.log(cantType.soemthign);
  launchMissiles(cantType.soehign);
}

@mhegazy
Copy link
Contributor

mhegazy commented Jan 18, 2017

@sandersn can you refresh and merge?

@sandersn sandersn merged commit 4759ade into master Jan 18, 2017
@sandersn sandersn deleted the property-access-for-string-index-sigs branch January 18, 2017 16:38
@sandersn
Copy link
Member Author

Done

niieani added a commit to niieani/typescript-vs-flowtype that referenced this pull request Feb 3, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants