【发布时间】:2020-07-27 19:05:59
【问题描述】:
interface FormikInstance {
touched: {[key: string]: boolean | undefined}
errors: {[key: string]: string | undefined}
status?: {[key: string]: string}
}
const useFormikErrors = (formik: FormikInstance) => {
const showErrors = (fieldName: string): boolean => {
const status = formik.status ? formik.status[fieldName] : undefined;
return !!formik.touched[fieldName] && (!!formik.errors[fieldName] || !!status);
}
const getErrors = (fieldName: string): string => {
const status = formik.status ? formik.status[fieldName] : undefined;
// errors is of type: string | undefined, but should be string
let errors = formik.errors[fieldName] === undefined ? '' : formik.errors[fieldName];
errors += status === undefined ? '' : status;
return errors;
}
return [showErrors, getErrors]
};
问题已在评论中标记。错误变量是string | undefined。打字稿是否考虑三元运算符,还是我在这里遗漏了一些明显的东西?
提前致谢。
【问题讨论】:
-
请注意,检查
undefined并不能排除所有“空”场景 - 它也可能是null或您可能不一定想要呈现的其他类似的虚假值。
标签: javascript typescript conditional-operator