首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当提供了具有正确接口的对象时,为什么所提供的参数不匹配调用目标的符号?

当提供了具有正确接口的对象时,为什么所提供的参数不匹配调用目标的符号?
EN

Stack Overflow用户
提问于 2016-02-17 22:02:29
回答 1查看 370关注 0票数 0

我的问题是为什么实现某些接口的对象不被应该接受接口作为参数的构造函数所接受。

在下面的示例中,有实现Subject接口的WeatherData类。还有CurrentConditionDisplay类,它在构造函数中接受Subject作为参数。

问题是WeatherData对象的实例不为CurrentConditionDisplay的构造函数所接受。TypeScript编译器只是大喊大叫

错误TS2346:提供的参数与调用目标的任何签名不匹配。

代码显示此错误:

提供的参数与调用目标的任何签名不匹配。(局部变量) weatherData: WeatherStation.WeatherData

CurrentConditionDisplay.ts

代码语言:javascript
复制
/// <reference path="DisplayElement.ts" />
/// <reference path="Observer.ts" />
/// <reference path="Subject.ts" />
module Display {
    export class CurrentConditionDisplay implements observer.Observer, DisplayElement {
        weatherData: observer.Subject;
        temperature: number;
        humidity: number;

        CurrentConditionDisplay(weatherData: observer.Subject) {
            this.weatherData = weatherData;
            this.weatherData.registerObserver(this);
        }
        // some code here
    }
}

WeatherData.ts

代码语言:javascript
复制
/// <reference path="Subject.ts" />
/// <reference path="Observer.ts" />
module WeatherStation {
    export class WeatherData implements observer.Subject {
        // some code here
    }
}

MyWeatherStation.ts

代码语言:javascript
复制
/// <reference path="WeatherData.ts" />
/// <reference path="CurrentConditionDisplay.ts" />
class MyWeatherStation {
    MyWeatherStation() {
        var weatherData: WeatherStation.WeatherData =
                new WeatherStation.WeatherData();
        var display: Display.CurrentConditionDisplay =
                new Display.CurrentConditionDisplay(weatherData); //<--- error is here
        weatherData.setMeasurements(10,20,30);
    }
}
new MyWeatherStation();

是的,我只是在玩Head First设计模式:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-17 22:06:35

在TypeScript或ES6中声明构造函数的语法是:

代码语言:javascript
复制
class SomeClass {
  constructor(your, args, here) { ... }
}

您已经尝试编写了C#版本:

代码语言:javascript
复制
class SomeClass {
  SomeClass(your, args, here) { ... }
}

这只会使代码有效(当方法名与封闭类名相同时不会发生特殊情况):

代码语言:javascript
复制
let x = new SomeClass();
x.SomeClass(my, arg, here);

您可能注意到在调试时没有运行任何构造函数代码;)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35468694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档