使用已实现接口的功能会产生 'not a function' 错误
using functions of an implemented interface creates 'not a function' error
我用变量和函数定义了一个接口。
当尝试使用为 class 实现的函数时,我得到“错误类型错误:...getPrice 不是函数”
class和接口的定义:
export interface Charge {
code: string;
name: string;
getPrice: (category: string) => number;
}
export class StorePrice implements Charge {
code: string;
name: string;
getPrice(category: string): number {
return 234;
}
}
组件:
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
charges: Charge[];
constructor() {
this.charges = [
{
code: "125",
name: "apple"
} as StorePrice,
];
}
asStorePrice(charge: Charge) {
return charge as StorePrice;
}
}
HTML我实际使用函数的地方:
<div>
<div *ngFor="let charge of charges">
{{asStorePrice(charge).getPrice()}}
</div>
</div>
问题出在 'as' 使用上。 'as' 只是转换
的另一种语法
<StorePrice> yourVariable;
使用 'as' 不会创建 class 的对象。如果你想在你的对象上获取getPrice函数,那么你需要正常实例化对象:
this.charges = [
new StorePrice("125, "apple)
]
Ofc,你需要在class.
中创建构造函数
问题是这样的:
this.charges = [
{
code: "125",
name: "apple"
} as StorePrice,
];
您可以创建一个 StorePrice 对象:
new StorePrice('125', 'apple');
与:
export class StorePrice implements Charge {
constructor(
public code: string,
public name: string
) {}
getPrice(category: string): number {
return 234;
}
}
我用变量和函数定义了一个接口。
当尝试使用为 class 实现的函数时,我得到“错误类型错误:...getPrice 不是函数”
class和接口的定义:
export interface Charge {
code: string;
name: string;
getPrice: (category: string) => number;
}
export class StorePrice implements Charge {
code: string;
name: string;
getPrice(category: string): number {
return 234;
}
}
组件:
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
charges: Charge[];
constructor() {
this.charges = [
{
code: "125",
name: "apple"
} as StorePrice,
];
}
asStorePrice(charge: Charge) {
return charge as StorePrice;
}
}
HTML我实际使用函数的地方:
<div>
<div *ngFor="let charge of charges">
{{asStorePrice(charge).getPrice()}}
</div>
</div>
问题出在 'as' 使用上。 'as' 只是转换
的另一种语法<StorePrice> yourVariable;
使用 'as' 不会创建 class 的对象。如果你想在你的对象上获取getPrice函数,那么你需要正常实例化对象:
this.charges = [
new StorePrice("125, "apple)
]
Ofc,你需要在class.
中创建构造函数问题是这样的:
this.charges = [
{
code: "125",
name: "apple"
} as StorePrice,
];
您可以创建一个 StorePrice 对象:
new StorePrice('125', 'apple');
与:
export class StorePrice implements Charge {
constructor(
public code: string,
public name: string
) {}
getPrice(category: string): number {
return 234;
}
}