首页 > 解决方案 > 采用多个列表类型的函数的打字稿错误-接口上不存在值

问题描述

我有如下定义的以下接口,一个基本接口和 2 个其他接口,这些接口扩展了这个基本接口,其中子接口作为属性。:-

请注意,一个接口有“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。

打字稿给我一个错误

- "valueType" is not available on ICustomFunctions and "returnType" is not available on IFieldDefinitions

请注意,一个接口有“valueType”,另一个有“returnType”

如何定义接口并在函数中以打字稿不会引发此错误的方式访问它。

标签: javascripttypescripttypescript-typings

解决方案


你可以投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;
}

推荐阅读