I am trying to derive a class to set a field as optional, with that field being required in the Base class.
e.g.
class Base {
param1! : string;
param2! : string;
}
class Derived extends Omit<Base, "param1">{
}
This results in error ts(2693):
'Omit' only refers to a type, but is being used as a value here.
In case this is an XY problem, what I am really trying to solve is:
- I have generated classes that get regenerated on every build (so I cannot modify them manually, or do something to include the modification when generating)
- The generated classes define all properties as Required (similar to
Base
above). - I need to add decorators to some of the generated methods and properties.
- I need to allow
Partial
instances of the Base class. (Ideally with the decorators added only once).
Ideally, I would extend the Base class, using Required
,Omit
,Pick
,Partial
in order to derive multiple classes omitting/requiring the correct properties.
I have almost given up on all this scaffolding/boilerplate stuff and want to manually write out the models/sql/REST by hand.
(I am new to typescript)
CodePudding user response:
TS has two scopes (worlds). First is for runtime values, second is for types. According to JS specification and docs
The
extends
keyword can be used to subclass custom classes as well as built-in objects.
It means, that after extends
, both TypeScript and JavaScript expect runtime value. This is why you are getting an error, because Omit is a pure type, it is getting erased during compilation.
Using Omit
in this case is aquivalent to this pure javascript:
class Derived extends {
}
This syntax is wrong.
Instead, you need to use implements
. THis keyword is from type scope and helps TS to validate class declaration.
class Base {
param1!: string;
param2!: string;
}
class Derived implements Omit<Base, "param1">{
param2!: string;
}
Regarding, decorators. Please provide a minimum reproducible example with decorators.