Typescript - 确保 id 存在于数组中
我有一个商店,我想在其中正确管理 ID。假设我有以下帖子商店:
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[];
// ...
};
答案#1
不,没有办法实现这一点。
这取决于运行时的动态,这是 TypeScript 无法检查的范围。TypeScript 无法判断当你设置 id 时,数组中也存在一个具有该 id 的项。
答案#2
你可以做的一件事是将你的帖子定义为 as const,这样编译器就可以在编译时推断帖子 ID。然而,在运行时无法进行这种类型检查。
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>;
};
