Typescript 对象数组,每一项都有一个属性
我正在集成 Google Ads Rest API。我想传递 UserIdentifier 到一个函数,其中每个对象只能有一个项目,因为它是 此 Google Ads API 例如:
f([{hashedEmail: "xxxxxx"}, {hashedPhoneNumber: "xxxxxx"}]) // OK
f([{hashedEmail: "xxxxxx", hashedPhoneNumber: "xxxxxx"}]) // Not Cool
此示例很接近,但我只想使用 Google Ads API 中提到的密钥UserIdentifier 类型。
提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您正在寻找的结构是 C 型联合。这意味着您的对象只具有所有列出的属性中的一个属性。可以轻松创建辅助泛型类型来生成此结构:
我们需要显式地使其他属性
未定义
并且可选,因为当您在联合的其他部分中指定不应该出现的属性时,TypeScript 不会出错实际上就在那儿。无论如何,这是调整为使用此解决方案的代码:TypeScript Playground 链接
It looks like the sort of structure you are looking for is a C-Style Union. This means that you have an object that only has one property present out of all of the listed ones. A helper generic type can easily be created to generate this structure:
We need to make the other properties explicitly
undefined
and optional because TypeScript does not error when you specify properties in other parts of a union when they should not actually be there. Anyways, here is your code adjusted to use this solution:TypeScript Playground Link