我在interface
文件中定义了d.ts
:
declare module myModule
{
interface IQedModel {
field: string | string[];
operator: string;
}
}
在anuglar控制器中,我实现了它:
vm.filters = <myModule.IQedModel>{
operator: 'and',
field: []
};
function populateFields() {
vm.filters.field = [];
angular.forEach(addedFilters, item => {
vm.filters.field.push(item.data); //<-- THIS LINE SHOWS ERRORS
});
}
错误是:
属性'push'在类型'string |上不存在串[]'
这里有什么问题?
答案 0 :(得分:2)
您可以使用泛型:
declare module myModule
{
interface IQedModel<T> {
field: T;
operator: string;
}
}
var filters = <myModule.IQedModel<Array<string>>>{
operator: 'and',
field: []
};
var filters2 = <myModule.IQedModel<string>>{
operator: 'and',
field: ""
};
filters.field.push(""); // works
// filters.field = "" // String not assignable to string[]
filters2.field = ""; // works
// filters2.field.push(""); // push does not exist on type string
或者:
declare module myModule
{
interface IQedModel<T> {
field: T;
operator: string;
}
interface ISingleFieldQedModel extends IQedModel<string> {}
interface IMultiFieldQedModel extends IQedModel<string[]> {}
}
var filters = <myModule.IMultiFieldQedModel>{
operator: 'and',
field: []
};
filters.field.push("");
// filters.field = "" // String not assignable to string[]
var filters2 = <myModule.ISingleFieldQedModel>{
operator: 'and',
field: ""
};
filters2.field = "";
// filters2.field.push(""); // push does not exist on type string
答案 1 :(得分:0)
因此,基于BGR注释,我需要首先转换为数组:
(<string[]>vm.filters.field).push(item.data);