类型“MyType”不满足约束“ObjectShape”。“MyType”类型中缺少“string”类型的索引签名

ldr*_*kis 14 typescript yup

所以,我最近升级了

  • "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();
Run Code Online (Sandbox Code Playgroud)

打字稿错误:

TS2344: Type 'MyType' does not satisfy the constraint 'ObjectShape'. Index signature for type 'string' is missing in type 'MyType'.
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

Vla*_*rov 2

不用指定对象的接口,而是使用 Record - 指定形状<Record<keyof MyType, yup.AnySchema>>。所以你的代码看起来像这样:

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();
Run Code Online (Sandbox Code Playgroud)

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