typescriptes2022

Can't overwrite field declarations without initialiser


I have a module which includes the following:

class FooBar {
    type: string;
}

class Foo extends FooBar {
    type: 'foo';
}

class Bar extends FooBar {
    type: 'bar';
}

(See my gist for the full module, as well as supporting config)

When I compile with tsc, I get the error:

main.ts:14:5 - error TS2612: Property 'type' will overwrite the base property in 'FooBar'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration.

14     type: 'foo';
       ~~~~

main.ts:20:5 - error TS2612: Property 'type' will overwrite the base property in 'FooBar'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration.

20     type: 'bar';
       ~~~~


Found 2 errors in the same file, starting at: main.ts:14

However I need those fields to not be annotated with declare and to not have an initialiser (for class validation/transformation purposes).

The error only appears when I set the Typescript target to ES2022 (it works with ES2021 and earlier)


Solution

  • Annotating the type in the base class as abstract avoids the error:

    abstract class FooBar {
        abstract type: string;
    }