typescript - JSON 模式的 anyOf 类型如何转换为打字稿?
问题描述
假设我们有这样的模式(我借用了 OpenAPI 3.0 格式,但我认为意图很明确):
{
"components": {
"schemas": {
"HasName": {
"type": "object",
"properties": {
"name": { "type": "string" }
}
},
"HasEmail": {
"type": "object",
"properties": {
"email": { "type": "string" }
}
},
"OneOfSample": {
"oneOf": [
{ "$ref": "#/components/schemas/HasName" },
{ "$ref": "#/components/schemas/HasEmail" }
]
},
"AllOfSample": {
"allOf": [
{ "$ref": "#/components/schemas/HasName" },
{ "$ref": "#/components/schemas/HasEmail" }
]
},
"AnyOfSample": {
"anyOf": [
{ "$ref": "#/components/schemas/HasName" },
{ "$ref": "#/components/schemas/HasEmail" }
]
}
}
}
}
基于这个模式和我到目前为止阅读的文档,我会表达类型OneOfSample
,AllOfSample
就像这样:
type OneOfSample = HasName | HasEmail // Union type
type AllOfSample = HasName & HasEmail // Intersection type
但是我将如何表达类型AnyOfSample
?基于此页面:https ://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/我会想到这样的事情:
type AnyOfSample = HasName | HasEmail | (HasName & HasEmail)
问题是如何在 typescript 中正确表达 JSON 模式中的 anyOf 类型?
解决方案
看起来“OneOf”的意思是“必须完全匹配一个”,而“AnyOf”的意思是“必须至少匹配一个”。原来,“至少一个”是一个比较基础的概念,对应符号所代表的联合运算(“包含或”) 。|
因此,上述问题的答案只是:
type AnyOfSample = HasName | HasEmail // Union type
与交集的进一步联合不会改变接受的值:
type AnyOfSample = HasName | HasEmail | (HasName & HasEmail)
因为联合只能添加元素,并且 的所有元素HasName & HasEmail
都已经存在于HasName | HasEmail
. 观察:
type HasName = { name: string }
type HasEmail = { email: string };
type AnyOfIntersection = HasName | HasEmail | (HasName & HasEmail)
type AnyOfWithout = HasName | HasEmail
const aI: AnyOfIntersection = { name: "", email: "" }; // of course
const aW: AnyOfWithout = { name: "", email: "" }; // also accepted
如果您要使用运算符来缩小值,您可能希望保留交集,in
这会产生技术上不正确但通常有用的假设,即如果不知道某个键存在于类型中,则该键不存在:
function processAnyOf(aI: AnyOfIntersection, aW: AnyOfWithout) {
if (("name" in aI) && ("email" in aI)) {
aI; // (HasName & HasEmail)
}
if (("name" in aW) && ("email" in aW)) {
aW; // never
}
}
当然,这意味着您对OneOfSample
. 这个操作更像是一个析取联合(“exclusive or”),虽然不完全是因为当你有三个或更多集合时,析取联合的通常定义意味着“匹配一个奇数”,这不是你想要的。顺便说一句,我找不到我们在这里讨论的析取联合类型的广泛使用的名称,尽管这里有一篇有趣的论文讨论了它。
那么,我们如何在 TypeScript 中表示“完全匹配”?这并不简单,因为它最容易根据类型的否定或减法构建,而 TypeScript 目前无法做到这一点。也就是说,你想说这样的话:
type OneOfSample = (HasName | HasEmail) & Not<HasName & HasEmail>; // Not doesn't exist
但这里没有任何Not
效果。因此,您所能做的就是某种解决方法……那么有什么可能呢?你可以告诉 TypeScript 一个类型可能没有特定的属性。例如,该类型NoFoo
可能没有foo
键:
type ProhibitKeys<K extends keyof any> = {[P in K]?: never};
type NoFoo = ProhibitKeys<'foo'>; // becomes {foo?: never};
您可以使用条件类型获取键名列表并从另一个列表中删除键名(即减去字符串文字):
type Subtract = Exclude<'a'|'b'|'c', 'c'|'d'>; // becomes 'a'|'b'
这使您可以执行以下操作:
type AllKeysOf<T> = T extends any ? keyof T : never; // get all keys of a union
type ProhibitKeys<K extends keyof any> = {[P in K]?: never }; // from above
type ExactlyOneOf<T extends any[]> = {
[K in keyof T]: T[K] & ProhibitKeys<Exclude<AllKeysOf<T[number]>, keyof T[K]>>;
}[number];
在这种情况下,ExactlyOneOf
需要一个类型的元组,并将表示元组中每个元素的联合,明确禁止其他类型的键。让我们看看它的实际效果:
type HasName = { name: string };
type HasEmail = { email: string };
type OneOfSample = ExactlyOneOf<[HasName, HasEmail]>;
如果我们OneOfSample
使用 IntelliSense 进行检查,它是:
type OneOfSample = (HasEmail & ProhibitKeys<"name">) | (HasName & ProhibitKeys<"email">);
这就是说“要么HasEmail
没有name
财产,要么HasName
没有email
财产。它有效吗?
const okayName: OneOfSample = { name: "Rando" }; // okay
const okayEmail: OneOfSample = { email: "rando@example.com" }; // okay
const notOkay: OneOfSample = { name: "Rando", email: "rando@example.com" }; // error
看起来像。
元组语法允许您添加三种或更多类型:
type HasCoolSunglasses = { shades: true };
type AnotherOneOfSample = ExactlyOneOf<[HasName, HasEmail, HasCoolSunglasses]>;
这检查为
type AnotherOneOfSample = (HasEmail & ProhibitKeys<"name" | "shades">) |
(HasName & ProhibitKeys<"email" | "shades">) |
(HasCoolSunglasses & ProhibitKeys<"email" | "name">)
如您所见,它正确地分配了被禁止的密钥。
还有其他方法可以做到这一点,但这就是我要继续的方式。这是一种解决方法,而不是完美的解决方案,因为在某些情况下它无法正确处理,例如具有相同键的两种类型,其属性是不同的类型:
declare class Animal { legs: number };
declare class Dog extends Animal { bark(): void };
declare class Cat extends Animal { meow(): void };
type HasPetCat = { pet: Cat };
type HasPetDog = { pet: Dog };
type HasOneOfPetCatOrDog = ExactlyOneOf<[HasPetCat, HasPetDog]>;
declare const abomination: Cat & Dog;
const oops: HasOneOfPetCatOrDog = { pet: abomination }; // not an error
在上面,ExactlyOneOf<>
未能递归到属性的pet
属性以确保它不是 aCat
和 a Dog
。这可以解决,但它开始变得比您可能想要的更复杂。还有其他边缘情况。这取决于你需要什么。
推荐阅读
- qt - C++ 和 QML:对象关系
- laravel - 拉拉维尔。如何在“FormRequest”中应用两个条件“required_if”,其中字段看起来像“books*pages*color”?
- expo - expo-camera 与 expo-barcode-scanner 的条码扫描性能
- javascript - 包含带有定义的单词的可用 txt 文件
- angular - Angular 材料 10:使日期范围选择器开放式
- javascript - 查找数组中的重复对
- sql - READ COMMITTED 或 SERIALIZABLE
- amazon-web-services - 从 AWS Educate 账户 Cloud9 控制台部署 SAM 脚本时出错
- python - 如何去除python pyqt5滚动条中的透明性
- node.js - 如何使用服务帐户访问 GSuite 电子邮件帐户的 GMAIL API