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

How do JSON schema's anyOf type translate to typescript?

假设我们有这样的模式(我借用了 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)

问题是如何在 typescriptJSON 模式中正确表达 anyOf 类型

看起来“OneOf”的意思是“必须完全匹配一个”,而“AnyOf”的意思是“必须匹配至少一个”。事实证明,“至少一个”是一个更基本的概念,对应于|符号所代表的union operation ("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,您可能希望保留交集,这使得技术上不正确但经常有用的假设是如果密钥 未知 出现在一个类型中,那么它是 not present:

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"), although not exactly because when you have three or more sets, the usual definition of a disjunctive union means "matches an odd number", which is not what you want. As an aside, I can't find a widely used name for the type of disjunctive union we're talking about here, although here's an interesting paper

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

表示“没有 name 属性 的 HasEmail,或者没有 email 属性 的 HasName。有用吗?

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

Playground link to code

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

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