JSON 模式的anyOf 类型如何转换为打字稿?

2024-03-04

假设我们有一个这样的模式(我借用了 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 and 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/ https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/我会想到这样的事情:

type AnyOfSample = HasName | HasEmail | (HasName & HasEmail)

问题是如何在打字稿中正确表达 JSON 模式中的 anyOf 类型?


看起来“OneOf”的意思是“必须匹配”exactlyone”,而“AnyOf”表示“必须匹配at least原来“至少一个”是一个比较基本的概念,对应的是union https://en.wikipedia.org/wiki/Union_(set_theory)手术 (”包含或 https://en.wikipedia.org/wiki/Logical_disjunction”)代表的是|象征。因此,您所提出的问题的答案只是:

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

如果您要使用,您可能需要保留交叉点the in缩小值的运算符 https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing,这做出了技术上不正确但通常有用的假设,即如果密钥是未知存在于一个类型中,那么它是not展示:

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。这个操作更像是一个析取联合 https://en.wikipedia.org/wiki/Symmetric_difference (“异或” https://en.wikipedia.org/wiki/Exclusive_or),尽管不完全是因为当您有三个或更多集合时,析取并的通常定义意味着“匹配奇数”,这不是您想要的。顺便说一句,我找不到我们在这里讨论的析取并类型的广泛使用的名称,尽管这里有一个有趣的论文 http://www.sfu.ca/%7Ejeffpell/papers/IGPLTernaryExclOr.pdf那个讨论它。

那么,我们如何在 TypeScript 中表示“完全匹配”呢?这并不简单,因为它最容易构建为negation https://github.com/Microsoft/TypeScript/issues/4196 or 减法 https://github.com/Microsoft/TypeScript/issues/4183类型,TypeScript 目前无法做到这一点。也就是说,你想说的是:

type OneOfSample = (HasName | HasEmail) & Not<HasName & HasEmail>; // Not doesn't exist

但没有Not这在这里有效。因此,你所能做的就是某种解决方法……那么有什么可能呢?你can告诉 TypeScript 类型可能没有特定属性。例如类型NoFoo可能没有foo key:

type ProhibitKeys<K extends keyof any> = {[P in K]?: never}; 
type NoFoo = ProhibitKeys<'foo'>; // becomes {foo?: never};

And you can使用条件类型获取键名称列表并从另一个列表中删除键名称(即减去字符串文字):

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: "[email protected] /cdn-cgi/l/email-protection" }; // okay
const notOkay: OneOfSample = { name: "Rando", email: "[email protected] /cdn-cgi/l/email-protection" }; // 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财产,以确保它不是两个Cat and a Dog。这个问题可以解决,但它开始变得比您想要的更复杂。还有其他边缘情况。这取决于你需要什么。

Playground 代码链接 https://www.typescriptlang.org/play?#code/C4TwDgpgBAEghgZwHJwLbQLxQN5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bVIxshM5BXVEAACqYDQAdK0qA3chL2PfstR4L6yi7SAH1Vf1TrfTgow3I8l0NlE0yzG4f0A8D9UYxA4OnlDh7BJC5CZvk9gAMKLjwz60DwiChE2IwIOUcD-ggJAUFU0D3mZii+uUwRHQNdUNTZaN+i1GSEO1Ia8BrCCs1E7PAjQXMwnGXWZuYABU+RSxUsuffLWCim9oVLWNq2TegizGOM-OC3G02zeatiteKo0RVW6puJ7jw+0L-tGIH-Kirr+uc9zcbO6uy3jRHZhR+7tIzeb5iZv+P5wOQ0BlzCBR4JQXB8LgOg0ML+ApWl06l1zFcbEbTYACJRHQcmOTRih168WNFuXzY2O4JDGlElB-B34Rd5XvdQMzcDJnWI9NmP9dY+gUQAO6z-Pi-LxLTOILmXFb7UIyQMAJAP9ON8IHfwAD3QT9cSQP9345nsH1L+D9lDkEAVgCyERGq2RVvYMB29tZfx-qbTu5dK5PSMqeag28hiv23l6H+0gtrPSiGAFuIDbJIOABAqBWNn4kDgMZVAeDIhgluoaX0HZZjkHpkAA

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSON 模式的anyOf 类型如何转换为打字稿? 的相关文章

随机推荐