英文:
Typescript - Ensure that id is present in array
问题
以下是您要翻译的内容:
我有一个商店,我想要正确管理 id。假设我有以下的 Posts 商店:
```typescript
type Post = {
id: number;
title: string;
body?: string;
}
type Store = {
postId: number | null;
posts: Post[];
addPost: (post: Omit<Post, "id">) => Promise<void>;
updatePost: (id: number, post: Partial<Post>) => Promise<void>;
};
如果选择了一篇文章,postId 就会设置为所选文章的 id。我想告诉 TypeScript postId 始终/应始终在 posts 中。这样我就可以确保如果我想找到正确的文章,它总是存在。
在 TypeScript 中是否有办法做到这一点?
类似于这样:
type Store = {
postId: (number in StoreType.posts.key<"id">) | null;
posts: Post[];
// ...
};
<details>
<summary>英文:</summary>
I have a Store in which I want to manage ids properly. Say I have the following Posts Store:
```typescript
type Post = {
id: number;
title: string;
body?: string;
}
type Store = {
postId: number | null;
posts: Post[];
addPost: (post: Omit<Post, "id">) => Promise<void>;
updatePost: (id: number, post: Partial<Post>) => Promise<void>;
};
If a post is selected, the postId is set to the selected post id. I want to tell typescript that this postId is always / should always be in posts. So I can be sure that if I want to find the proper post, it's always there.
Is there any way in typescript to do this?
Something like this:
type Store = {
postId: (number in StoreType.posts.key<"id">) | null;
posts: Post[];
// ...
};
答案1
得分: 2
没有,无法实现这一点。
这取决于运行时动态,超出了TS检查的范围。TS无法确定当您设置id
时,是否还有一个具有该id的数组项。
英文:
No, there is no way to achieve this.
This depends on runtime dynamics which are out of scope for TS to check. There is no way for TS to figure out that when you're setting the id
you are also having an item in the array with that id.
答案2
得分: 1
One thing you could do is define your posts as const
so the compiler can infer the post ids at compiler time. However, it's not possible to do that kind of type checking at runtime.
const posts = [
{
id: 3,
title: "Post 5",
body: "some description"
},
{
id: 42069,
title: "Post 42069",
body: "some description"
},
{
id: 666,
title: "Post 666",
body: "some description"
}
] as const;
type Store = {
postId: (typeof posts)[number]["id"]; // 3 | 42069 | 666
posts: Post[];
addPost: (post: Omit<Post, "id">) => Promise<void>;
updatePost: (id: number, post: Partial<Post>) => Promise<void>;
};
英文:
One thing you could do is define your posts as const
so the compiler can infer the post ids at compiler time. However, it's not possible to do that kind of type checking at runtime.
const posts = [
{
id: 3,
title: "Post 5",
body: "some description"
},
{
id: 42069,
title: "Post 42069",
body: "some description"
},
{
id: 666,
title: "Post 666",
body: "some description"
}
] as const;
type Store = {
postId: (typeof posts)[number]["id"]; // 3 | 42069 | 666
posts: Post[];
addPost: (post: Omit<Post, "id">) => Promise<void>;
updatePost: (id: number, post: Partial<Post>) => Promise<void>;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论