【问题标题】:Require fields in FormData using TypeScript使用 TypeScript 要求 FormData 中的字段
【发布时间】:2022-09-27 17:35:37
【问题描述】:

我想让FormData (documentation) 接口与指定的必填字段。所以我想使用 TypeScript 来检查我的 formData 是否包含所有必填字段。

export interface AddRequest {
  image: Blob;
  username: string;
}

// This is invalid
export interface AddRequestApi extends FormData {
  image: FormDataEntryValue;
  username: FormDataEntryValue;
}

所以我可以这样做:

export const mapRequest = (request: AddRequest): AddRequestApi => {
  const { image, username } = request;

  const formData = new FormData();
  formData.append(\'image\', image);
  formData.append(\'username\', username);

  // I want my ts compiler to check if returned formData has required fields
  // that should be stated in AddRequestApi type (or interface)
  return formData;
};
  • 在底部放一个简单的问题
  • Typescript 的类型检查在运行时不起作用,因此您不能使用 typescript 接口来检查是否有人发布了正确的数据。您仍然必须使用if 语句来查看是否存在某些数据以及它是什么类型。
  • 多次.append()调用的方式意味着代码只能在运行时检查,而不是编译时(这意味着TS无法检查它)

标签: typescript


【解决方案1】:

正如@Fabian Lauer 所说:

多个 .append() 调用的方法意味着代码只能在运行时检查,而不是编译时(这意味着 TS 无法检查它)

现在,有一些方法可以使用 TS 实现运行时类型检查。

看看这个博客 https://levelup.gitconnected.com/how-we-use-our-typescript-type-information-at-runtime-6e95b801cfeb

验证——使用另一个同样出色的工具,另一个 JSON Schema Validator 或 ajv,我们可以在运行时验证任何对象,只需传入对象和我们的模式。我们甚至会以一种我们可以通过编程方式使用的格式获得错误输出,例如针对无效字段在表单上显示错误、自动修复无效属性等。

【讨论】:

    【解决方案2】:

    像这样的东西?

    type MyFormFields = "image" | "username";
    
    interface MyFormData extends FormData {
        append(name: MyFormFields, value: string | Blob, fileName?: string): void
    }
    
    
    function bar(data: MyFormData) {
        const image = new Blob();
        const username = "myusername";
        data.append("image", image)
        data.append("username", username);
        data.append("something", "not working"); 
                    // Argument of type '"something"' is not assignable to parameter of type 'MyFormFields'.
    }
    

    FormData.append() 的接口是

    append(name: string, value: string | Blob, fileName?: string): void
    

    因此,当您覆盖附加功能的接口时,请尝试仅将名称参数限制为您的自定义必填字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2017-08-06
      • 2020-04-05
      • 2021-09-01
      • 2020-05-29
      • 2018-02-20
      • 1970-01-01
      相关资源
      最近更新 更多