【问题标题】:Type 'MyType' does not satisfy the constraint 'ObjectShape'. Index signature for type 'string' is missing in type 'MyType'类型 \'MyType\' 不满足约束 \'ObjectShape\'。类型 \'MyType\' 中缺少类型 \'string\' 的索引签名
【发布时间】:2022-10-05 21:24:51
【问题描述】:

所以,我最近升级了

  • \"yup\": \"^0.29.1\" => \"yup\": \"^0.32.11\"
  • \"@types/yup\": \"^0.29.3\" => \"@types/yup\": \"^0.29.13\",

现在我所有的Schemas 都坏了。我将提供一个示例,打字稿正在哭泣:

export interface MyType {
  id: number;
  name: string;
  description: string | null;
}

export const mySchema = yup
  .object<MyType>({
    id: yup.number().required(),
    name: yup.string().trim().required().max(50),
    description: yup.string().trim().max(200).defined(),
  })
  .required();

打字稿错误:

TS2344: Type \'MyType\' does not satisfy the constraint \'ObjectShape\'. Index signature for type \'string\' is missing in type \'MyType\'.

我在这里想念什么?

  • 你有没有去 yup 项目看看是否有任何升级说明或 BC 中断?
  • @Evert 我在更改日志中发现了一些东西,上面写着“BREAKING CHANGE: plain objects and arrays are no long cast to strings automatically\",但我怀疑它与我面临的问题有关
  • 看起来像一个已知问题。已在 1.x 测试版中修复:github.com/jquense/yup/issues/1510

标签: typescript yup


【解决方案1】:

不要指定对象的接口,而是使用 Record - &lt;Record&lt;keyof MyType, yup.AnySchema&gt;&gt; 对形状执行此操作。所以你的代码看起来像这样:

export const mySchema = yup
  .object().shape<Record<keyof MyType, yup.AnySchema>>({
    id: yup.number().required(),
    name: yup.string().trim().required().max(50),
    description: yup.string().trim().max(200).defined(),
  })
  .required();

到目前为止,我还没有找到更好的解决方案。

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2019-09-19
    • 2019-02-10
    • 2023-03-15
    • 2018-10-16
    相关资源
    最近更新 更多