我目前正在将一段代码转换为 TypeScript 并遇到一些类型问题yup。我尝试了多种方法并参考了yup关于 TypeScript 支持的文档来解决这个问题,但无济于事。
https://github.com/jquense/yup/blob/master/docs/typescript.md
这是我的代码示例:
import { object, Asserts, string } from 'yup';
interface BaseBootstrapSchema {
APPLICATION_NAME: string;
LOG_PATH: string;
}
const bootstrapValidationSchema = object<BaseBootstrapSchema>().shape({ // error 1 here
LOG_PATH: string().required("The 'LOG_PATH' ENV variable is required"),
APPLICATION_NAME: string().required("The 'APPLICATION_NAME' ENV variable is required"),
});
interface BootstrapSchema extends Asserts<typeof bootstrapValidationSchema> {}
module.exports = (schema: BootstrapSchema) =>
new Promise((resolve, reject) =>
schema
.validate(process.env, { abortEarly: false }) // error 2 here
.then(() => resolve(true))
.catch((error: any) => {
if (error.errors.length > 1) {
reject(new Error(`${error.message},\n${error.errors.join(',\n')}`));
} else {
reject(new Error(error.message));
}
})
);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
错误 1:
类型 'BaseBootstrapSchema' 不满足约束 'Record<string, AnySchema<any, any, any> | 参考 | 懒惰<任何,任何>>'。“BaseBootstrapSchema”类型中缺少索引签名。
错误 2:
类型“BootstrapSchema”上不存在属性“validate”。
我尝试了几种方法来纠正这个问题,但没有一个真正有效。
帮助表示赞赏。
cat*_*uzz 28
按照此处的yup 指南,您应该按如下方式更改代码:
import { object, SchemaOf, string } from 'yup';
interface BaseBootstrapSchema {
APPLICATION_NAME: string;
LOG_PATH: string;
}
const bootstrapValidationSchema: SchemaOf<BaseBootstrapSchema> = object({
LOG_PATH: string().required("The 'LOG_PATH' ENV variable is required"),
APPLICATION_NAME: string().required("The 'APPLICATION_NAME' ENV variable is required"),
});
module.exports = (schema: SchemaOf<BaseBootstrapSchema>) =>
new Promise((resolve, reject) =>
schema
.validate(process.env, { abortEarly: false })
.then(() => resolve(true))
.catch((error: any) => {
if (error.errors.length > 1) {
reject(new Error(`${error.message},\n${error.errors.join(',\n')}`));
} else {
reject(new Error(error.message));
}
})
);
Run Code Online (Sandbox Code Playgroud)
实际上你根本不需要const bootstrapValidationSchema,因为你将它传递给你正在导出的节点模块,但我可能误解了你在这里想要实现的目标。
尝试一下。
| 归档时间: |
|
| 查看次数: |
2780 次 |
| 最近记录: |