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

Generic parameter types are incorrectly inferred as { } #26809

Closed
2A5F opened this issue Aug 31, 2018 · 3 comments
Closed

Generic parameter types are incorrectly inferred as { } #26809

2A5F opened this issue Aug 31, 2018 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@2A5F
Copy link

2A5F commented Aug 31, 2018

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

@AlCalzone
Copy link
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!

@2A5F
Copy link
Author

2A5F commented Aug 31, 2018

But why would it be {} instead of an error

@2A5F 2A5F closed this as completed Aug 31, 2018
@AlCalzone
Copy link
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants