Skip to content

Generic parameter types are incorrectly inferred as { } #26809

Closed

Description

@2A5F

TypeScript Version: 3.0.1, vscode 1.26.1

Search Terms:

Code

interface A<R> {
    a(): R
}

function some1<R>(a: A<R>): R {
    return null
}

function some2<R, D extends A<R>>(a: D): R {
    return null
}

let out1 = some1({
    a() {
        return 'asd'
    }
})

let out2 = some2({
    a() {
        return 'asd'
    }
})

Expected behavior: out1: string, out2: string

Actual behavior: out1: string, out2: {}

Playground Link

Activity

  1. AlCalzone commented on Aug 31, 2018

    @AlCalzone
    Contributor

    Seems there is not enough context for TS to infer R in some2, since you are not passing any argument with type R. You can fix this by explicitly telling TypeScript to infer R from the interface:

    interface A<R> {
        a(): R
    }
    
    declare function some2<D extends A<any>>(a: D): D extends A<infer R> ? R : any;
    
    let out2 = some2({
        a() {
            return 'asd'
        }
    })
    // out2 is string!
  2. 2A5F commented on Aug 31, 2018

    @2A5F
    Author

    But why would it be {} instead of an error

  3. AlCalzone commented on Aug 31, 2018

    @AlCalzone
    Contributor

    As far as I understand, {} is the default when inference fails. This keeps the type-checking enabled - as opposed to any, which doesn't.

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

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions