Skip to content

Object literals use contextual type for this when available and ignore type of literal itself. #15157

Closed
@sandersn

Description

@sandersn

Object literals with no contextual type use the type of the literal itself for this. However, when there is a contextual type, that gets used for this to the exclusion of the literal's own type. The type for this should actually be the intersection of the contextual type and the literal's own type.

class B { b: any }
class D extends B { d: any }
type Ctx = { m(): B, m2(): any }
let o: Ctx = {
    m() {
        return new D()
    },
    m2() {
        this.m()/**/
    }
}

this.m() should be of type D but is actually of type B.

I don't know how important this is; the current behaviour is pretty good but it did break a couple of times in our real-world code base. See comments on the original PR #14141 for details. MockJax and an Angular test broke.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions