【发布时间】:2017-06-23 08:57:07
【问题描述】:
我已经定义了接口IDictionary如下:
interface IDictionary<T = any> {
[key: string]: T;
}
然后我将这个类型 T 传递给 db.update() 函数,该函数定义为:
public update<T = IDictionary>(path: string, value: T) {
return this.ref(path).update(value);
}
当我尝试编译此文件时,我收到以下错误:
src/shared/Model.ts (64,7): 类型参数 '{ lastUpdated: string; }' 不可分配给“T”类型的参数。 (2345)
考虑到IDictionary<any> 类型是默认的“T”,我不明白为什么这不会被认为是有效的。是不是我做错了什么?
演示错误的完整示例:
interface IDictionary<T = any> {
[key: string]: T;
}
function dbupdate<T = IDictionary>(path: string, value: T) {
return this.ref(path).update(value);
}
abstract class Model<T = IDictionary> {
public update(updateWith: IDictionary) {
const reference = 'bar';
return dbupdate<T>(
reference,
{
...updateWith,
...{ lastUpdated: 'baz' }
}
);
}
}
【问题讨论】:
-
问题不在于您发布的代码,而在于您如何使用它。所附图像未显示所有相关代码,仅显示其结尾。这是什么
T? -
在上图中,您可以在悬停对话框中看到类型分辨率...默认为
IDictionary<any> -
请使用其余相关代码更新您的问题。如果有一些其他人可以用来重现您的问题,那就太好了。
-
好的,不确定要包含哪些内容,所以我将整个文件添加到 gist 此处:gist.github.com/ksnyde/806b2e3439157d55bd0cf70c8ec5aa88