如何在TypeScript中定义对象数组?

时间:2020-02-18 15:09:30

标签: typescript

我是Typescript plz帮助的新手

我正在努力理解以下代码的错误消息。我只是想定义一个对象数组,似乎无法弄清楚为什么它不起作用?

interface FieldClass {
  id: string,
    name: string,
    type: string,
    label: string
}

const fields: FieldClass[] = [{
  id: 'name',
  name: 'input',
  type: 'name',
  label: 'Name',
}, {
  id: 'email',
  name: 'email',
  type: 'email',
  label: 'Email',
}, {
  id: 'password',
  name: 'password',
  type: 'password',
  label: 'Password',
}, , {
  id: 'confirm-password',
  name: 'confirm-password',
  type: 'confirm-password',
  label: 'Confirm password',
}];

错误消息:

Type '({ id: string; name: string; type: string; label: string; } | undefined)[]' is not assignable to type 'FieldClass[]'.
  Type '{ id: string; name: string; type: string; label: string; } | undefined' is not assignable to type 'FieldClass'.
    Type 'undefined' is not assignable to type 'FieldClass'.  TS2322

1 个答案:

答案 0 :(得分:1)

您在此处输入错误:

  label: 'Password',
}, , {
  id: 'confirm-password',

应该用一个逗号

  label: 'Password',
}, {
  id: 'confirm-password',