英文:
Initialize Pinia store with a type
问题
免责声明:我是一个JS初学者
我正在使用Pinia存储和Python REST API同步一个对象。我想只声明一次类型,而不必在存储中重复。
export const useTicketStore = defineStore('ticket', {
state: () => ({
id: null,
status: "",
subject: "",
email: "",
department: null,
ticketType: null,
}),
actions: {
save() {
const action = this.id ? axios.patch : axios.post
const url = this.id ? `/api/tickets/${this.id}` : "/api/tickets"
action(url, this).then((response) => {
this.$patch(response.data)
})
}
}
})
在我的应用程序中,我使用了一种类型声明以保持一致性:
interface Ticket {
id: number | null,
status: string,
subject: string,
email: string,
department: number | null,
ticketType: number | null,
}
我想做的是像这样:
export const useTicketStore = defineStore('ticket', {
state: () => ({
...Ticket
}),
actions: {
...
})
使用上面的示例会导致奇怪的错误:
Uncaught SyntaxError: 请求的模块'/src/types/ticket.ts'未提供名为'Ticket'的导出项
英文:
Disclaimer: I am an JS beginner
I am synchronizing an object with pinia store and a python REST API. I Want to declare a type only once and not have to mirror it in the store.
export const useTicketStore = defineStore('ticket', {
state: () => ({
id: null,
status: "",
subject: "",
email: "",
department: null,
ticketType: nulll,
}),
actions: {
save() {
const action = this.id ? axios.patch : axios.post
const url = this.id ? `/api/tickets/${this.id}` : "/api/tickets"
action(url, this).then((response) => {
this.$patch(response.data)
})
}
}
})
Throughout my app I use an type declaration for consistancy:
interface Ticket {
id: number | null,
status: string,
subject: string,
email: string,
department: number | null,
ticketType: number | null,
}
What I would like to do is something like this
export const useTicketStore = defineStore('ticket', {
state: () => ({
...Ticket
}),
actions: {
...
})
using the example above results in an strange error:
Uncaught SyntaxError: The requested module '/src/types/ticket.ts' does not provide an export named 'Ticket'
答案1
得分: 1
你遇到的错误表明你尝试导入 Ticket
的文件没有默认导出,因此如果你没有定义默认导出,你必须以这种方式导入:
import {Ticket} from '...'; // 带有花括号
关于你想要实现的目标,该函数返回一个对象(键-值对),它可能是 Ticket
类型,但你不能用 Ticket
替代它,因为 Ticket
是一种类型,不是一个对象。<br>
你仍然可以为函数定义返回类型,但这不会避免指定返回对象的值:
state: (): Ticket => ({
id: null,
status: "",
subject: "",
email: "",
department: null,
ticketType: null,
})
英文:
The error you are encoutring tells that the file from where you try to import Ticket
does not have a default export so if you didn't define a default export you have to import this way:
import {Ticket} from '...'; // with curly brackets
about what you want to achieve, the function is returning an object (key-value), it may be of type Ticket
but you cannot replace it with Ticket
because Ticket
is a type, not an object. <br>
you still can define a return type for the function, but this will not avoid specifying the values of the returned object:
state: (): Ticket => ({
id: null,
status: "",
subject: "",
email: "",
department: null,
ticketType: null,
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论