首页 > 解决方案 > typescript子类构造函数不同参数

问题描述

我今天跌跌撞撞,我不确定为什么 TS 允许为构造函数创建具有不同参数的子类

class C1 {
  constructor (protected foo: number[] = []){}
}
class C2 extends C1 {
  constructor (protected bar: number){ // why not alert here?
    super()
  }
}

标签: typescripttypescript-typings

解决方案


这是大多数面向对象编程语言的行为。因此,允许子类具有与其父类不同的输入参数是有意的。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(...)

推荐阅读