【发布时间】:2022-01-11 22:24:52
【问题描述】:
当扩展一个类时,我可以很容易地向它添加一些新属性。
但是,当我扩展一个基类时,如果我想为基类的一个对象(一个简单对象的属性)添加新属性怎么办?
这是一个带有一些代码的示例。
基类
type HumanOptions = {
alive: boolean
age: number
}
class Human {
id: string
options: HumanOptions
constructor() {
this.id = '_' + Math.random()
this.options = {
alive: true,
age: 25,
}
}
}
派生类
type WizardOptions = {
hat: string
} & HumanOptions
class Wizard extends Human{
manaLevel: number
options: WizardOptions // ! Property 'options' has no initializer and is not definitely assigned in the constructor.
constructor() {
super()
this.manaLevel = 100
this.options.hat = "pointy" // ! Property 'options' is used before being assigned.
}
}
现在,正如您从嵌入式 cmets 中看到的那样,这会激怒 TypeScript。 但这适用于 JavaScript。那么实现这一目标的正确 ts 方法是什么?如果没有,是我的代码模式本身的问题吗?什么模式适合这个问题?
也许你想知道为什么我想要options 对象中的这些属性。它可能非常有用!例如:只有options 中的属性可以通过某些UI 进行编辑。因此,其他一些代码可以在类中动态查找 options 并在 UI 上公开/更新它们,同时诸如 id 和 manaLevel 之类的属性将被单独保留。
注意
我知道我可以为向导做到这一点:
class Wizard extends Human{
manaLevel: number
options: {
hat: string
alive: boolean
age: number
}
constructor() {
super()
this.manaLevel = 100
this.options = {
alive: true,
age: 25,
hat: "pointy"
}
}
}
而且它有效。但是代码不是很干,我必须手动管理选项继承(这在复杂的应用程序中并不理想)。
【问题讨论】:
-
Clorofilla,当您说“但这在 JavaScript 中有效”时,您的意思是它在运行时在由 TypeScript 编译器输出的 JavaScript 中有效吗?或者你的意思是你手工编写了类似的 JavaScript 并且它在那里工作?对于in a comment chain 的含义存在分歧。
-
我指的是第一种情况。 TS 报错,但 JS 输出运行没有错误。
标签: typescript class object inheritance extends