gpt4 book ai didi

Typescript - 确保 id 存在于数组中

转载 作者:行者123 更新时间:2023-12-03 07:52:22 29 4
gpt4 key购买 nike

我有一个商店,我想在其中正确管理 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 总是/应该总是在帖子中。因此,我可以确定,如果我想找到合适的帖子,它总是在那里。

typescript 有什么办法可以做到这一点吗?

类似这样的事情:

type Store = {
postId: (number in StoreType.posts.key<"id">) | null;
posts: Post[];
// ...
};

最佳答案

不,没有办法实现这一点。

这取决于运行时动态,这超出了 TS 检查的范围。 TS 无法确定当您设置 id 时,数组中也有具有该 id 的项目。

关于Typescript - 确保 id 存在于数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76873318/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com