【问题标题】:React with yup error Type 'undefined' cannot be used as an index type. TS2538反应 yup 错误类型“未定义”不能用作索引类型。 TS2538
【发布时间】:2021-09-20 05:19:46
【问题描述】:

我正在使用 yup 使表单无效,当它们无效时,我希望此函数返回错误,但它总是在 validationErrors[error.path] 中给出错误,它得到 Type 'undefined' cannot be used as索引类型

import { ValidationError } from 'yup';

interface Errors {
  [key: string]: string;
}

export default function getValidationErrors(err: ValidationError): Errors {
  const validationErrors: Errors = {};

  err.inner.forEach(error => {
    validationErrors[error.path] = error.message;
  });

  return validationErrors;
}


----------


Console error: 

    Type 'undefined' cannot be used as an index type.  TS2538
    11 |   err.inner.forEach((error) => {
  > 12 |     validationErrors[error.path] = error.message;
       |                      ^
    13 |   });
    14 |
    15 |   return validationErrors;

【问题讨论】:

    标签: reactjs typescript yup unform


    【解决方案1】:

    这里的问题是ValidationErrorpath 字段是可选的declared

    export default class ValidationError extends Error {
      value: any;
      path?: string; // path?: string | undefined
      type?: string;
      errors: string[];
    
      params?: Params;
    
      inner: ValidationError[];
    ...
    

    这意味着即使它出现在错误对象上,它的值也可以(从打字稿的角度来看)是undefined

    所以在使用error.path 作为计算索引值之前,您必须检查它不是undefined。您可以按预期进行检查:

      err.inner.forEach(error => {
        if (typeof error.path !== 'undefined') {
          validationErrors[error.path] = error.message;
        }
      });
    

    或者,如果您绝对确定它可能永远不会是 undefined,您可以只使用 type assertnon-null assertion operator !

      err.inner.forEach(error => {
        validationErrors[error.path!] = error.message;
      });
    

    但请记住,如果您的建议错误,则使用类型断言,您将在错误对象中获得 validationErrors.undefined 字段。

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2019-10-14
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2019-07-30
      • 2023-01-20
      相关资源
      最近更新 更多