[英]Omitting properties when extending a class
I am trying to derive a class to set a field as optional, with that field being required in the Base class.我正在尝试派生一个类以将字段设置为可选,该字段在基类中是必需的。
eg例如
class Base {
param1! : string;
param2! : string;
}
class Derived extends Omit<Base, "param1">{
}
This results in error ts(2693):这会导致错误 ts(2693):
'Omit' only refers to a type, but is being used as a value here. 'Omit' 仅指一种类型,但在这里用作值。
In case this is an XY problem, what I am really trying to solve is:如果这是一个 XY 问题,我真正想要解决的是:
Base
above).生成的类将所有属性定义为必需(类似于上面的Base
)。Partial
instances of the Base class.我需要允许基类的Partial
实例。 (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.理想情况下,我会扩展 Base 类,使用Required
、 Omit
、 Pick
、 Partial
以派生多个省略/需要正确属性的类。
I have almost given up on all this scaffolding/boilerplate stuff and want to manually write out the models/sql/REST by hand.我几乎放弃了所有这些脚手架/样板的东西,并想手动写出模型/sql/REST。
(I am new to typescript) (我是打字稿的新手)
TS has two scopes (worlds). TS 有两个范围(世界)。 First is for runtime values, second is for types.第一个是运行时值,第二个是类型。 According to JS specification and docs根据 JS 规范和文档
The
extends
keyword can be used to subclass custom classes as well as built-in objects.extends
关键字可用于子类化自定义类以及内置对象。
It means, that after extends
, both TypeScript and JavaScript expect runtime value.这意味着,在extends
之后,TypeScript 和 JavaScript 都期望运行时值。 This is why you are getting an error, because Omit is a pure type, it is getting erased during compilation.这就是您收到错误的原因,因为Omit是纯类型,它在编译期间被删除。 Using Omit
in this case is aquivalent to this pure javascript:在这种情况下使用Omit
等同于这个纯 javascript:
class Derived extends {
}
This syntax is wrong.这种语法是错误的。 Instead, you need to use implements
.相反,您需要使用implements
。 THis keyword is from type scope and helps TS to validate class declaration. TH 这个关键字来自类型范围,帮助 TS 验证类声明。
class Base {
param1!: string;
param2!: string;
}
class Derived implements Omit<Base, "param1">{
param2!: string;
}
Regarding, decorators.关于,装饰师。 Please provide a minimum reproducible example with decorators.请提供带有装饰器的最小可重现示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.