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

TypeScript not considering ternary operator with undefined

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。打字稿是否考虑三元运算符,或者我在这里遗漏了一些明显的东西? 提前致谢。

不幸的是,

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

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