Skip to content

Cannot subclass class-like types with accessors. #40733

Closed
@ewlsh

Description

@ewlsh

TypeScript Version: 4.1.0-beta

Search Terms: accessor property subclass mapped types

Code

type Types = 'boolean' | 'unknown' | 'string';

type Properties<T extends { [key: string]: Types }> = {
    readonly [key in keyof T]: T[key] extends 'boolean' ? boolean : T[key] extends 'string' ? string : unknown
}

type AnyCtor<P extends object> = new (...a: any[]) => P

declare function classWithProperties<T extends { [key: string]: Types }, P extends object>(properties: T, klass: AnyCtor<P>): {
    new(): P & Properties<T>;
    prototype: P & Properties<T>
};

const Base = classWithProperties({
    x: 'boolean',
    y: 'string',
    z: 'unknown'
}, class Base {
});

class MyClass extends Base {
    constructor() {
        super();
    }

    // Errors with: 'x' is defined as a property in class 'Base & Properties<{ x: "boolean"; y: "string"; z: "unknown"; }>', but is 
    // overridden here in 'MyClass' as an accessor. (2611)
    get x() {
        return false;
    }
}

const mine = new MyClass();
const value = mine.x;

Expected behavior:

I can create subclasses of mapped types when the mapped type defines a property and the subclass defines an accessor.

Actual behavior:

TypeScript gives an error saying you can't override a property with an accessor.

Playground Link: Link

Related Issues: I know this is related to the change in behavior in 4.0 to universally disallow accessors overriding properties.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issueIn 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