【问题标题】:Using TypeScript super()使用 TypeScript super()
【发布时间】:2016-06-22 02:08:27
【问题描述】:

我正在尝试在 TypeScript 中扩展一个类。我在编译时不断收到此错误:“提供的参数与调用目标的任何签名都不匹配。”我尝试将 super 调用中的 artist.name 属性引用为 super(name) 但不起作用。

您的任何想法和解释将不胜感激。谢谢 - 亚历克斯。

class Artist {
  constructor(
    public name: string,
    public age: number,
    public style: string,
    public location: string
  ){
    console.log(`instantiated ${name}, whom is ${age} old, from ${location}, and heavily regarded in the ${style} community`);
  }
}

class StreetArtist extends Artist {
  constructor(
    public medium: string,
    public famous: boolean,
    public arrested: boolean,
    public art: Artist
  ){
    super();
    console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
  }
}

interface Human {
  name: string,
  age: number
}

function getArtist(artist: Human){
  console.log(artist.name)
}

let Banksy = new Artist(
  "Banksy",
   40,
  "Politcal Graffitti",
  "England / Wolrd"
)

getArtist(Banksy);

【问题讨论】:

    标签: javascript oop typescript


    【解决方案1】:

    超级调用必须为基类提供所有参数。构造函数不是继承的。注释掉艺术家,因为我想这样做时不需要它。

    class StreetArtist extends Artist {
      constructor(
        name: string,
        age: number,
        style: string,
        location: string,
        public medium: string,
        public famous: boolean,
        public arrested: boolean,
        /*public art: Artist*/
      ){
        super(name, age, style, location);
        console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
      }
    }
    

    或者,如果您希望 art 参数填充基本属性,但在这种情况下,我想实际上不需要在 art 参数上使用 public,因为这些属性将被继承,并且只会存储重复数据。

    class StreetArtist extends Artist {
      constructor(
        public medium: string,
        public famous: boolean,
        public arrested: boolean,
        /*public */art: Artist
      ){
        super(art.name, art.age, art.style, art.location);
        console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
      }
    }
    

    【讨论】:

    • 如果你将 pubic 添加到每个构造函数参数,这个参数将被分配给子级和父级
    • 我确实打算用艺术填充基类:艺术家。第二个解决方案无缝地工作。非常感谢。
    • 很高兴能够提供帮助。 @mortezaT,你是对的,它意味着前四个参数没有公开。我不知道如果您将 StreetArtist 转换为 Artist 并访问名称例如会发生什么,它们会相同吗?它隐藏了基础属性吧?
    • 第二个解决方案值得注意。您基本上是在创建两个具有相同信息的艺术家对象。来自 c# 世界,这对我来说似乎有点不对劲,但它可以工作:) 对于打字稿,也许我会使用一个接口作为 art 参数,并使用一个对象初始化器作为接口之后的{ name: 'aoue', ... }
    • @CodyBugsteina 据我所知。看起来有请愿书让它或多或少像 Java 规范一样隐含。 github.com/Microsoft/TypeScript/issues/5910
    猜你喜欢
    • 2021-03-17
    • 2020-02-05
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2012-03-21
    • 2014-02-26
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多