【发布时间】:2020-07-15 20:02:10
【问题描述】:
我有一个模态数据接口
interface ModalData {
...
payload: any; // At any given time, this payload might be a string or number or boolean;
...
}
在模态数据payload中可能有不同的类型,为此我创建了另一种类型:
type IPayLoad = string | number | boolean;
现在,当我在我的代码中使用这种类型时,我遇到了以下错误。
问题是我不喜欢将any 类型设置为上面的有效负载。
但如果我将其设置为 IPayLoad 类型,则会出现以下错误。
this.service.saveString(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'string'.
this.service.saveNumber(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'number'.
this.service.saveBool(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'boolean'.
服务中的调用函数如下:
public saveString(res: string): void {}
public saveNumber(res: number): void {}
public saveBool(res: boolean): void {}
【问题讨论】:
-
你怎么知道调用哪个方法?
标签: javascript typescript types interface