【问题标题】:TypeScript not considering ternary operator with undefinedTypeScript 不考虑未定义的三元运算符
【发布时间】: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


【解决方案1】:

不幸的是,检查 nested 属性的类型并不能缩小其类型。您可以通过先将值提取到独立变量中来修复它(这也有助于使代码更加干燥):

const fieldErrors = formik.errors[fieldName];
let errors = fieldErrors === undefined ? '' : fieldErrors;
errors += status === undefined ? '' : status;
return errors;

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多