【问题标题】:No index signature with a parameter of type 'string' was found on type 'X'在“X”类型上找不到带有“字符串”类型参数的索引签名
【发布时间】:2021-10-16 06:17:06
【问题描述】:

我想用打字稿创建我的猫鼬插入验证,但我遇到了一个错误

这里是我的参数类型:

type OperationType = 'Insert' | 'Update' | 'Delete';

type Operator =  'Exists' | 'NotExists' | '>=' | '=<' | '>' | '<' |'true' | 'fasle'; 

type Properties<T> = Partial<T> | [Partial<T>];

type ValidateProp<T> = {fieldName:T  ,operator:Operator};

type Validation<V> = [ValidateProp<V>];  

enter image description here

const checkValidation = <T extends Document,K extends keyof T>(ValidateProps:Validation<K>,properties:Properties<T>,model:Model<T>) => {

if(ValidateProps.length){

if(typeof properties === 'object'){

   Object.keys(properties).forEach((prop) => {
    const validProp = ValidateProps.find(f => f.fieldName === prop);
    if(validProp){
      
      let entity: Partial<T> & Record<string, T[keyof T]> = {};
      
      entity[prop] =  properties[prop];
      

      switch (validProp.operator) {
        case 'Exists':
          model.find(entity)
          break;
      
        default:
          break;
      }
    }
  });

}

}

  1. 列表项

}

在 Object.key 循环道具中不被视为属性中的键索引 错误

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“属性”类型。 在“Properties”类型上找不到带有“字符串”类型参数的索引签名。ts(7053)

【问题讨论】:

  • Please consider replacing or supplementing images of text with the actual plain text。理想情况下,您应该提供纯文本代码作为 minimal reproducible example 适合放入像 The TypeScript Playground 这样的独立 IDE 中,以便其他人可以自己演示问题。
  • 嗨 Faizan,你遇到了什么错误?您可以将错误消息添加为文本吗?我无法从屏幕截图中读取它。
  • 嗨,迈克尔,我遇到了这种类型的错误(元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“属性”。没有索引签名在 'Properties'.ts(7053) 类型上找到了“字符串”类型的参数
  • 你可以放大它以获得正确的结果,我被困在弱者身上,请指导我在哪里出错
  • 您好 Faizan,考虑编辑您的帖子以使其更具可读性。 Stackoverflow 中的帖子应该具有一定的质量水平。见stackoverflow.com/help/how-to-ask

标签: typescript mapping


【解决方案1】:

对象“prop”是 Object.keys() 返回的数组中的一个元素,因此是一个字符串,因此无需将其转换为任何元素。这应该可以解决屏幕截图中显示的错误。

【讨论】:

  • 没有强制转换我得到了那种类型的错误(元素隐式有一个'any'类型,因为'string'类型的表达式不能用于索引类型'Properties'。没有索引签名在“Properties”.ts(7053)) 类型上找到了“字符串”类型的参数
猜你喜欢
  • 2020-01-06
  • 1970-01-01
  • 2019-10-27
  • 2021-11-27
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多