Skip to content

Contextually type class property initializers by extends/implements types #3667

@RyanCavanaugh

Description

@RyanCavanaugh

When a property has exactly one type from an extends or implements clause, we should contextually type that property's initializer by the type from the clause. For example:

interface ThingListener {
    handleEvent: (x: MouseEvent) => void;
}

class Foo implements ThingListener {
    handleEvent = x => {
        // No error, but this code is incorrect
        console.log(x.timestamp);
    }
}

Ideally we could take this one step further when widening. The following behavior is also undesirable:

interface HasLength {
    length: number
}

class Foo implements HasLength {
    // length: any, not really what we intended
    length = undefined;
}

var x = new Foo();
x.length = 'wat'; // should not be allowed

e.g. #3666

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueDesign LimitationConstraints of the existing architecture prevent this from being fixedSuggestionAn idea for TypeScriptWon't FixThe severity and priority of this issue do not warrant the time or complexity needed to fix it

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions