我的问题是为什么实现某些接口的对象不被应该接受接口作为参数的构造函数所接受。
在下面的示例中,有实现Subject接口的WeatherData类。还有CurrentConditionDisplay类,它在构造函数中接受Subject作为参数。
问题是WeatherData对象的实例不为CurrentConditionDisplay的构造函数所接受。TypeScript编译器只是大喊大叫
错误TS2346:提供的参数与调用目标的任何签名不匹配。
代码显示此错误:
提供的参数与调用目标的任何签名不匹配。(局部变量) weatherData: WeatherStation.WeatherData
CurrentConditionDisplay.ts
/// <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
/// <reference path="Subject.ts" />
/// <reference path="Observer.ts" />
module WeatherStation {
export class WeatherData implements observer.Subject {
// some code here
}
}MyWeatherStation.ts
/// <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设计模式:)
发布于 2016-02-17 22:06:35
在TypeScript或ES6中声明构造函数的语法是:
class SomeClass {
constructor(your, args, here) { ... }
}您已经尝试编写了C#版本:
class SomeClass {
SomeClass(your, args, here) { ... }
}这只会使代码有效(当方法名与封闭类名相同时不会发生特殊情况):
let x = new SomeClass();
x.SomeClass(my, arg, here);您可能注意到在调试时没有运行任何构造函数代码;)
https://stackoverflow.com/questions/35468694
复制相似问题