匹配

match 函数提供了一种强大的方式来处理不同类型的输入,并根据输入类型返回相应的输出,就像一个类型安全的 switch 语句。

案例记录 API

定义匹配器的最简单方法是使用 ArkType 定义字符串作为键,对应的处理程序作为值:

import { match } from "arktype"

const  = match({
	"string | Array": v => v.length,
	number: v => v,
	bigint: v => v,
	default: "assert"
})

// 一旦指定了 `default`(无论是作为案例还是通过 .default() 方法),匹配定义就完成了

("abc") // 3
([1, 2, 3, 4]) // 4
(5n) // 5n
// ArkErrors: 必须是对象、字符串、数字或 bigint(实际为 boolean)
(true)

在这个例子中,sizeOf 是一个匹配器,接受字符串、数组、数字或 bigint 作为输入。它返回字符串和数组的长度,以及数字和 bigint 的值。

default 接受以下 4 个值之一:

  • "assert": 接受 unknown,如果没有匹配的案例则抛出错误
  • "never": 基于推断的案例接受输入,如果没有匹配则抛出错误
  • "reject": 接受 unknown,如果没有匹配的案例则返回 ArkErrors
  • (data: In) => unknown: 直接处理不匹配其他案例的数据

案例将按照它们指定的顺序进行检查,无论是作为对象字面量键还是通过链式方法。

流式 API

match 函数还提供了一个流式 API。这对于非字符串可嵌入的定义非常方便:

import { match } from "arktype"

// 案例记录和流式 API 可以轻松组合使用
const  = match({
	string: v => v.length,
	number: v => v,
	bigint: v => v
})
	// 匹配任何具有数值长度属性的对象并提取它
	.case({ length: "number" }, o => o.length)
	// 对所有其他数据返回 0
	.default(() => 0)

("abc") // 3
({ name: "David", length: 5 }) // 5
(null) // 0

使用 in 缩小输入范围,使用 at 进行属性匹配

import { match } from "arktype"

type  =
	| {
			id: 1
			oneValue: number
	  }
	| {
			id: 2
			twoValue: string
	  }

const  = match
	// .in 允许您指定匹配器允许的 TypeScript 输入类型
	.in<>()
	// .at 允许您指定一个键,在该键处将匹配您的输入
	.at("id")
	.match({
		1: o => `${o.oneValue}!`,
		2: o => o.twoValue.length,
		default: "assert"
	})

({ id: 1, oneValue: 1 }) // "1!"
({ id: 2, twoValue: "two" }) // 3
({ oneValue: 3 })
TypeScript: Property 'id' is missing in type '{ oneValue: number; }' but required in type '{ id: 1; oneValue: number; }'.

On this page