我在
store
中定义了 store/stores.js
,如下所示:
import { get, writable, readable } from "svelte/store";
export const labelStore = writable([])
我的程序中的标签都是
LabelType
类型,定义如下:
type LabelType = {
imageURL: string;
frameNumber: number;
pointX: number;
pointY: number;
action: "contact" | "detach";
agent: "hand" | "object";
}
在我的
main
部分中,我有一个循环,它迭代 LabelStore
中的标签并将它们呈现到屏幕上,如下所示:
<main>
{#each $labelStore as lbl, index}
<div>Index {index}</div>
<div>Image URL: {lbl.imageURL}</div>
<div>Frame #: {lbl.frameNumber}</div>
<div>Point x: {lbl.pointX}</div>
<div>Point y: {lbl.pointY}</div>
<div>Agent: {lbl.agent}</div>
<div>Action: {lbl.action}</div>
<div>--------------------------------</div>
{/each}
</main>
我面临的问题是一个错误,告诉我我尝试访问的属性不存在:
Property 'imageURL' does not exist on type 'never'.ts(2339)
Property 'frameNumber' does not exist on type 'never'.ts(2339)
...
stores.js
文件中指定类型,但它不起作用。我想将
lbl
循环内的 #each
转换为 <LabelType>
。正确的做法是什么?
提前致谢
TypeScript 无法推断传递给
writable
的数组的类型,因为它是一个空数组。要显式为其指定类型,您可以将该类型作为类型参数传递给 writable
:
type LabelType = {
imageURL: string;
frameNumber: number;
pointX: number;
pointY: number;
action: "contact" | "detach";
agent: "hand" | "object";
}
export const labelStore = writable<LabelType[]>([])