使用界面时发生TypeScript错误2304

gc0ot86w  于 2022-11-30  发布在  TypeScript
关注(0)|答案(2)|浏览(146)

在一个Angular 项目上工作,我创建了一个接口文件,在其中我做了两件事:
定义接口:

export interface tableHeader {
    roundNumber: string;
    eighteenHoleScore: string;
    nineHoleScore: string;
    courseRating: string;
    slopeRating: string;
    scoreDifferential: string;
}

创建一个变量以保存字符串数组:

export const roundHeader = [
    roundNumber: 'Round Number',
    eighteenHoleScore: '18 Hole Score',
    nineHoleScore: '9 Hole Score',
    courseRating: 'Course Rating',
    slopeRating: 'Slope Rating',
    scoreDifferential: 'Score Differential'
]

我得到了上述2304错误为我的每个变量创建的roundHeader常量.我看了整个网站,并没有看到任何回答这个问题,我发现在谷歌上有很多东西有关'要求',但在这种情况下,它与要求无关.
我只是尝试创建一个接口来定义每个变量类型,然后在同一个文件中创建静态文本,这样我就可以将此静态文本导出到我的应用程序的多个页面。
任何帮助都是非常感谢的

ogsagwnx

ogsagwnx1#

1.您需要定义roundHeader类型。
1.数组将仅包含,而不包含键值
如果要使用带有数组的接口,请使用对象数组:

interface tableHeader {
  roundNumber: string;
  eighteenHoleScore: string;
  nineHoleScore: string;
  courseRating: string;
  slopeRating: string;
  scoreDifferential: string;
}

const roundHeader: tableHeader[] = [
  {
    roundNumber: "Round Number",
    eighteenHoleScore: "18 Hole Score",
    nineHoleScore: "9 Hole Score",
    courseRating: "Course Rating",
    slopeRating: "Slope Rating",
    scoreDifferential: "Score Differential",
  },
];

Playground链接
您的替代答案:
如果您需要静态文本,为什么不使用enum?:

enum TableHeader{
    roundNumber= "Round Number",
    eighteenHoleScore= "18 Hole Score",
    nineHoleScore= "9 Hole Score",
    courseRating= "Course Rating",
    slopeRating= "Slope Rating",
    scoreDifferential= "Score Differential",
   }

   const somewhereNeedsRoundNumber = TableHeader.roundNumber
6yt4nkrj

6yt4nkrj2#

也许你的案例就是我们的朋友贾斯特里亚·拉赫马特所展示的。然而,在这里澄清一些事情:
当你声明你的接口时,一切都很好,但是当你创建你的const时,你没有显式地说那个const是什么类型,通过export const roundHeader: tableHeader可以做什么(喜欢用大写字母开始类型/接口名称)。
另一个问题是,您的roundHeader是一个数组,您试图向其中添加key-value对,而正确的做法是创建一个JS对象而不是该数组,结果如下:

export const roundHeader: TableHeader = {
    roundNumber: 'Round Number',
    eighteenHoleScore: '18 Hole Score',
    nineHoleScore: '9 Hole Score',
    courseRating: 'Course Rating',
    slopeRating: 'Slope Rating',
    scoreDifferential: 'Score Differential'
};

如果您真的需要包含这些字段的对象数组,只需按照Jastria的答案操作,得到类似于以下内容的结果:

export const roundHeader: TableHeader[] = [
    {
        roundNumber: "Round Number",
        eighteenHoleScore: "18 Hole Score",
        nineHoleScore: "9 Hole Score",
        courseRating: "Course Rating",
        slopeRating: "Slope Rating",
        scoreDifferential: "Score Differential",
    },
    // ...
    // other objects with the same fields
]

相关问题