我希望FormData
(文档)接口具有指定的必需字段。因此,我想使用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;
};
发布于 2021-11-17 12:10:05
@Fabian Lauer说:
多个.append()调用的方法意味着只能在运行时检查代码,而不能在编译时检查(这意味着TS不能检查它)
现在,有一些方法可以实现运行时类型检查与TS。
看看这个博客https://levelup.gitconnected.com/how-we-use-our-typescript-type-information-at-runtime-6e95b801cfeb
验证--使用另一个同样令人敬畏的工具,另一个JSON模式Validator或ajv,我们只需传入对象和我们的模式就可以在运行时验证任何对象。我们甚至可以获得一种格式的错误输出,这种格式可以编程地用于在表单上针对无效字段显示错误、自动修复无效属性等。
发布于 2022-09-27 09:35:37
像这样吗?
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
因此,当您重写附加函数的接口时,请尝试将名称参数限制在您的自定义必需字段上。
https://stackoverflow.com/questions/70003975
复制相似问题