TypeScript不考虑具有未定义的三元运算符

时间:2020-04-14 22:13:02

标签: javascript typescript conditional-operator

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。打字稿会考虑三元运算符,还是我在这里遗漏了一些明显的东西? 预先感谢。

1 个答案:

答案 0 :(得分:1)

不幸的是,检查嵌套属性的类型不会缩小其类型。您可以通过先将值提取到独立变量中来解决此问题(这也有助于使代码更干燥):

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