是的,可选对象成员的打字稿类型错误

yup typescript type error of optional object member

我想为对象定义一个 yup 模式,包含可选的内部对象 属性;

type Inner = {
  size: number;
  price: number;
};

type Container = {
  inner?: Inner;
};

const containerSchema: yup.SchemaOf<Container> = yup.object().shape({
  inner: yup
    .object({
      size: yup.number().defined(),
      price: yup.number().defined(),
    })
    .optional(),
});

出于某种原因,我收到了一个误导性的打字稿错误:

const containerSchema: ObjectSchemaOf<Container, never>
Type 'ObjectSchema<Assign<ObjectShape, { inner: OptionalObjectSchema<{ size: DefinedNumberSchema<number | undefined, AnyObject>; price: DefinedNumberSchema<number | undefined, AnyObject>; }, AnyObject, TypeOfShape<...>>; }>, AnyObject, TypeOfShape<...>, AssertsShape<...>>' is not assignable to type 'ObjectSchemaOf<Container, never>'.
  Type 'Assign<ObjectShape, { inner: OptionalObjectSchema<{ size: DefinedNumberSchema<number | undefined, AnyObject>; price: DefinedNumberSchema<number | undefined, AnyObject>; }, AnyObject, TypeOfShape<...>>; }>' is not assignable to type '{ inner: BaseSchema<Maybe<Inner | undefined>, AnyObject, Inner | undefined>; }'.
    The types of 'inner.__inputType.size' are incompatible between these types.
      Type 'number | undefined' is not assignable to type 'number'.
        Type 'undefined' is not assignable to type 'number'.ts(2322)

如果我通过删除问号使内部 属性 成为必填项,Typescript 错误就会消失。

您必须像这样在对象内部定义对象:

type Inner = {
  size: number;
  price: number;
};

type Container = {
  inner?: Inner;
};

const containerSchema: yup.SchemaOf<Container> = yup.object().shape({
  inner: yup.object().shape({
    size: yup.number().defined(),
    price: yup.number().defined(),
  }).optional()
});

要求使用.object().shape()。参见 How I can validate object inside objects in yup?