我有如下定义的接口,一个基本接口和两个扩展这个基本接口的其他接口,其中有子接口作为属性。: -
请注意,一个接口有'valueType',另一个有'returnType'
interface IBase {
id:string;
label:string;
value:string;
expanded:boolean;
isGroup:boolean;
}
interface IFieldDefinitions extends IBase {
children: Array<IFiedValues>;
}
interface ICustomFunctions extends IBase{
children: Array<ICustomFunction & {id:string;label:string;value:string;}>
}
interface ICustomFunction{
name:string;
args: Array<IFunctionArgs>;
returnType: string;
description: string;
array: boolean;
}
interface IFiedDefValues {
id: string;
name: string;
value: string;
label: string;
valueType: string;
columnType: string;
description: string;
}
现在我有一个简单的函数来根据它们的returType/valueType对customFunctions和fieldDefinitions进行分组。首先,我为这个分组编写了单独的函数,并意识到这两个分组函数是相似的。因此,我想创建一个单独的函数,它接受项目列表并返回分组项目,如下所示:
public get groupFieldsByType(){
return computeGrouping(fields,"fields");
}
public get groupFunctionsByType(){
return computeGrouping(functions,"functions");
}
函数定义:-
function computeGrouping(listItems:IFieldDefinitions[] | ICustomFunctions[],type:string ){
let modifiedFieldDefs = [] as IFieldListboxItem[];
listItems.forEach(items => {
const filteredStringValues = items.children.filter(item => type === 'fields' ? item.valueType === 'Text' : item.returnType === 'String');
const filteredNumericValues = items.children.filter(item => type === 'fields' item.valueType === 'Number' : item.returnType === 'Number');
// other computations go in here and I return the grouped array;
return modifiedFieldDefs;
}
}
现在您可以看到,根据我传递的类型,我检查valueType或returnType。
Typescript抛出了一个错误
- "valueType" is not available on ICustomFunctions and "returnType" is not available on IFieldDefinitions
请注意,一个接口有'valueType',另一个有'returnType'
如何定义接口并在函数中访问它,而使typescript不抛出此错误?
可以强制转换item
:
function computeGrouping(listItems:IFieldDefinitions[] | ICustomFunctions[],type:string ){
let modifiedFieldDefs = [] as IFieldListboxItem[];
listItems.forEach(items => {
const filteredStringValues = items.children.filter(item => type === 'fields' ? (item as IFiedDefValues).valueType === 'Text' : (item as ICustomFunction).returnType === 'String');
const filteredNumericValues = items.children.filter(item => type === 'fields' ? (item as IFiedDefValues).valueType === 'Number' : (item as ICustomFunction).returnType === 'Number');
});
return modifiedFieldDefs;
}