typescript - typescript子类构造函数不同参数
问题描述
我今天跌跌撞撞,我不确定为什么 TS 允许为构造函数创建具有不同参数的子类
class C1 {
constructor (protected foo: number[] = []){}
}
class C2 extends C1 {
constructor (protected bar: number){ // why not alert here?
super()
}
}
解决方案
这是大多数面向对象编程语言的行为。因此,允许子类具有与其父类不同的输入参数是有意的。super 调用促进了与基类的一致性。
旁白: 但在你的情况下,也许课程并不是你真正想要的?这是另一种可能更适合您的上下文的模式。它允许强制执行一致的构造函数参数:
type YourThing = {
someProp: "prop"
someFn: () => void
someGetter: () => "A" | "B"
}
type CommonParams = "CommonParams"
type ThingBuilder = (params: CommonParams) => YourThing
const builderOne: ThingBuilder = params => {
let privateMutableThing: "A" | "B" = "A"
return {
someProp: "prop",
someFn: () => {
if (privateMutableThing === "A") {
privateMutableThing = "B"
}
},
someGetter: () => privateMutableThing,
}
}
const builderTwo: ThingBuilder = params => {
return {
someProp: "prop",
someFn: () => {},
someGetter: () => "A",
}
}
const extension = (builder: ThingBuilder): ThingBuilder =>
params => {
const base = builder(params)
// some additional stuff
return {
// extended version of base
}
}
const builderThree = extension(builderOne)
// Usage: No `new` needed.
const thing1 = builderOne(...)
const thing2 = builderTwo(...)
const thing3 = builderThree(...)
推荐阅读
- python - 我正在尝试使用“pip”安装枕头
- ios - iOS 14.0 及更高版本奇怪的自动布局行为
- angular - 角度材料表未填充数据
- c - 如何在“mac os catalina 10.15.6”上更改 zsh 终端线宽
- drools - optaplanner 中的简单流口水规则优化失败
- string - 字符串连接在 Fortran 中不起作用
- react-native - 为什么 setState 值设置为某个值后仍然为空?
- python - 有哪些选项可以让使用 Selenium 和 Tor 浏览器更快地访问网站?
- scheme - 如何使此代码对矩形起作用?(方案/打字球拍)
- reporting-services - SSRS:显示文本而不是值