【问题标题】:How do JSON schema's anyOf type translate to typescript?JSON 模式的 anyOf 类型如何转换为打字稿?
【发布时间】:2019-03-21 01:35:49
【问题描述】:

假设我们有这样的架构(我借用了 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" }
        ]
      }
    }
  }
}

基于此架构和我目前阅读的文档,我将表达类型 OneOfSampleAllOfSample 如下:

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 类型

【问题讨论】:

  • 我认为您无法在 TypeScript 中准确描述 anyOf。 TS 中的联合不是精确/排他的,因此即使 HasName | HasEmail 也将允许将 { name, email } 分配给它。不过,也许有一些条件类型的魔力会起作用……read this issue

标签: typescript jsonschema


【解决方案1】:

看起来“OneOf”的意思是“必须匹配完全一个”,而“AnyOf”的意思是“必须匹配至少一个”。原来,“至少一个”是一个更基础的概念,对应|符号所代表的union操作(“inclusive or”)。因此,您的问题的答案只是:

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 operator to narrow values,您可能希望保留交集,这会产生技术上不正确但通常有用的假设,即如果密钥未知出现在类型,那么它存在:

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 的定义不正确。这个操作更像disjunctive union ("exclusive or"),虽然不完全是因为当你有三个或更多集合时,析取联合的通常定义意味着“匹配一个奇数”,这不是你想要的。顺便说一句,我找不到我们在这里讨论的分离联合类型的广泛使用的名称,尽管这里有一个讨论它的interesting paper

那么,我们如何在 TypeScript 中表示“完全匹配”?这并不简单,因为它最容易根据类型的 negationsubtraction 构建,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]>;

如果我们用 IntelliSense 检查OneOfSample,它是:

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&lt;&gt; 无法递归到 pet 属性的属性以确保它不是CatDog。这可以解决,但它开始变得比您可能想要的更复杂。还有其他边缘情况。这取决于你需要什么。

Playground link to code

【讨论】:

  • 很好的答案。我还要注意 HasName | HasEmail 将接受 partial 对象,只要 one 类型完全满足...我不确定是否真的适合精确的anyOf 要求。但它和我猜你能得到的一样接近。
  • 我严重误解了联合类型 (|)。我本来希望我的OneOfSample 是正确的。
  • 我不认为HasName | HasEmailHasName | HasEmail | (HasName &amp; HasEmail) 是一样的,见playground 我认为HasName | HasEmail | (HasName &amp; HasEmail) 是正确的anyOf
  • 我同意@Gregor这里HasName | HasEmailHasName | HasEmail | (HasName &amp; HasEmail)绝对不同
  • @Safareli 感谢您的反馈。我已经编辑了答案,希望能解决您对HasName | HasEmailHasName | HasEmail | (HasName &amp; HasEmail) 之间差异的担忧。您不会找到一个可分配给一个也不能分配给另一个的值,因此它们描述的是同一组值;但是编译器确实允许基于键的存在进行一些不合理的缩小,在某些情况下会以不同的方式对待它们,因此根据使用情况,您可能确实希望在那里有交集。
【解决方案2】:

实际上,将 JSON Schema 表示为类型定义的想法是一种范式不匹配。 JSON Schema 不是为这种事情而设计的。它正试图将一个圆钉锤入一个方孔。它永远不会完全合身。

JSON Schema 旨在转换为可用于验证 JSON 文档的函数。

【讨论】:

  • 我也有同样的感觉:D
  • 这不是 imo 的答案。您对 JSON Schema 被设计用于运行时验证是正确的,但是如果验证函数通过,则该验证函数必须返回一些内容。如何在验证后键入该对象是 TypeScript 的一个有效问题和用例。
  • @Gricey 该验证函数返回真或假。我会做类似function isMyType(n: unknown) =&gt; n is MyType 的事情。您如何定义MyType 与模式要验证的预期类型有关。架构实际上并未定义该类型,仅定义验证约束。您必须根据带外信息确定类型。公认的答案很棒,但希望人们可以退后一步,看看所有那种类型的体操都不是架构作者想要的,而是做一些更实际的事情。
  • @JasonDesrosiers 完全正确。这个问题是关于开发人员如何创建MyType,OP 正在寻求帮助,在打字稿中表示 something。问题中没有任何内容使其无效,并且您的答案作为评论可能会更好,因为它没有按要求回答问题。
  • 问题不在于定义特定类型。如果是,那我会同意你的。这个问题特别是关于在打字稿中表达anyOf 的正确方法。没有正确答案。这取决于作者的上下文和意图。
猜你喜欢
  • 2019-06-05
  • 2021-11-07
  • 1970-01-01
  • 2023-02-10
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-17
  • 2019-03-23
相关资源
最近更新 更多