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

Contextually type this in object literals in JS #17252

Merged

Conversation

sandersn
Copy link
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
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
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

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
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
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