Epic Wink
Epic Wink

Reputation: 865

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)

Upvotes: 2

Views: 942

Answers (3)

doydoy44
doydoy44

Reputation: 5782

As the error message suggests, you can add declare like this :

class FooBar {
    type: string;
}

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

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

Upvotes: 1

Vivick
Vivick

Reputation: 4991

As the error indicates, you need to add an initializer:

type = "foo" as const

Tho this should suffice, TS really want you to make properties abstract if you want the type to be override as well.

Upvotes: 0

Epic Wink
Epic Wink

Reputation: 865

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

abstract class FooBar {
    abstract type: string;
}

Upvotes: 1

Related Questions