Skip to content

Contextually type this in object literals in JS#17252

Merged
sandersn merged 2 commits into
masterfrom
contextually-type-this-in-object-literals-in-javascript
Jul 18, 2017
Merged

Contextually type this in object literals in JS#17252
sandersn merged 2 commits into
masterfrom
contextually-type-this-in-object-literals-in-javascript

Conversation

@sandersn
Copy link
Copy Markdown
Member

Previously, this would only get a contextual type inside object literals with --noImplicitThis turned on in Typescript files.

Fixes #16184

Previously, `this` would only get a contextual type inside object
literals with `--noImplicitThis` turned on in Typescript files.
@DanielRosenwasser
Copy link
Copy Markdown
Member

This is likely too restrictive - I've previously argued that what you really want is the contextual type & Record<string, any>.

@sandersn
Copy link
Copy Markdown
Member Author

Isn't Record<string, any> equivalent to { [s: string]: any }? JS objects include a string indexer now, so this is legal:

const o = {
    p: 12,
    m() {
        return this.p + this.x
    }
}

And o: { p: number; m(): any; [x: string]: any }. Does that address the scenario you had in mind?

method() {
this;
this.prop;
this.method;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a test for unknown property. Should be no error, get any.

Copy link
Copy Markdown
Member

@weswigham weswigham left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a sucker for changes that are only one line before tests. Nice one!

@sandersn sandersn merged commit fb89d47 into master Jul 18, 2017
@sandersn sandersn deleted the contextually-type-this-in-object-literals-in-javascript branch July 18, 2017 17:18
@sandersn
Copy link
Copy Markdown
Member Author

From conversation with @Andy-MS, note that if you make a call like this:

transformsPropertiesIntoMethods({
  p: 12,
  m() {
    return this.p()
  }
})

Then you will get an error with // @ts-check because the contextual type comes from the object literal but should come from the call to transformsPropertiesIntoMethods. You'll need to install types for the transformer function (ember or vue are popular libraries that work like this).

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 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.

4 participants