Skip to content

Different inference behavior between method and function syntax as opposed to arrow functions. #38623

Closed

Description

TypeScript Version: 4.0.0-dev.20200516

Search Terms: object literal inference arrow function method

Expected behavior: M in inferred as { foo: () => void; }

Actual behavior:: When using function or method syntax M is inferred as unknown. Using arrow functions works fine.

Related Issues: #32230 But that specific case seems fixed

Code

function make<M>(o: { mutations: M,  action: (m: M) => void }) { }

make({
   mutations: {
       foo () { } // Nope
       // foo: function () { } // Nope 
       // foo: () => { } // OK
   },
   action: (a) => { a.foo() }
})
Output
"use strict";
function make(o) { }
make({
    mutations: {
        // foo () { } // Nope
        // foo: function () { } // Nope 
        foo: () => { } // OK
    },
    action: (a) => { a.foo(); }
});
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Activity

  1. HerringtonDarkholme commented on Aug 3, 2020

    @HerringtonDarkholme
    Contributor

    Personally I don't think this is a bug but rather an improvement.
    A method signature will contextually type the object literal itself because this in method is the containing object literal. But an arrow function does not have this.

    A user-side fix would be annotate this explicitly:

    function make<M>(o: { mutations: M,  action: (m: M) => void }) { }
    
    make({
       mutations: {
           foo(this: {}) { } // OK
       },
       action: (a) => { a.foo() }
    })

    However, we can skip the contextual typing if this isn't accessed in the method.

    https://www.typescriptlang.org/play/?ts=4.0.0-dev.20200516#code/GYVwdgxgLglg9mABAWwIYGsCmAeAsgPgAo4AuRAbxRClVgQGczcAaRRVaeMMw5JgSkQBefIgBucGABNEAX0GVZAWABQqtFkLlVbKjTphGFHbt3A4cQlAAWMI+HRg4AdzAK5iAPSfEAeXQmcsyBHAY8qIIiFOwAdOaWgsoq8kA

  2. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions