我有一个角5应用程序,我希望有一个接口来定义这样的函数:
interface PersonInfo {
getName(): string;
}我想要另一个接口,它将有一个函数,它的函数之一返回上述的类型:
interface Parser{
getPersonInfo(document: string): PersonInfo;
}然后,我想在我的主要组件中以某种方式使用它,如以下所示。
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements PersonInfo, Parser {
constructor() {
const pi: PersonInfo = this.getPersonInfo('test');
console.log(pi.getName());
}
public getName(): string{
return 'getname';
}
public getPersonInfo(document: string): PersonInfo{
const pi: PersonInfo = {
getName(){
return 'getPersonInfo - getName()';
}
};
return pi;
}
}问题是,在console.log(ci.getName());中,我的站点给了我一个TypeError: ci.getName is not a function错误。
我不知道如何让getPersonInfo设置名字..。然后getName()返回那个名字..。然后在构造函数(或其他函数)中调用这些函数并获取名称。有什么帮助吗?
发布于 2018-08-17 08:25:01
我看到的第一个问题是,您向TSC断言创建的"pi“对象符合"PersonInfo",但它缺少"getName()”属性。
试试这个:
public getPersonInfo(document: string): PersonInfo {
const pi: PersonInfo = {
getName() {
return 's';
}
};
return pi;
}在可能的情况下,避免使用"foo as Bar“语法,这似乎是一种覆盖,允许开发人员将值投给编译器无法保证有效的类型。
https://stackoverflow.com/questions/51887074
复制相似问题