泛型

关键字

此表包含默认 type API 中可用的所有泛型关键字。

AliasDescription
Excludeexclude branches of a union like Exclude("boolean", "true")
Extractextract branches of a union like Extract("0 | false | 1", "number")
Mergemerge an object's properties onto another like Merge(User, { isAdmin: "true" })
Omitomit a set of properties from an object like Omit(User, "age")
Partialmake all named properties of an object optional like Partial(User)
Pickpick a set of properties from an object like Pick(User, "name | age")
Recordinstantiate an object from an index signature and corresponding value type like Record("string", "number")
Requiredmake all named properties of an object required like Required(User)

语法

泛型可以通过三种方式之一来声明和实例化。

定义

import { type } from "arktype"

const  = type("<t>", { box: "t" })

// hover me!
const  = ({ cat: { isAlive: "boolean" } })

约束参数

参数定义中的所有语法以及对泛型参数的所有引用都具有完全的类型安全性,并像任何内置关键字一样支持自动补全。约束可以像 TypeScript 一样使用,以限制可以传递给泛型的参数,并允许该参数与 > 等运算符一起使用。

import { type } from "arktype"

const  = type("<arr extends unknown[]>", "arr > 0")

const  = ("number[]")

作用域

指定作用域中泛型的特殊语法如下:

import { scope } from "arktype"

const  = scope({
	"box<t, u>": {
		box: "t | u"
	},
	bitBox: "box<0, 1>"
}).export()

const  = .bitBox({ box: 0 })

调用

import { type } from "arktype"

const  = type("Extract<0 | 1, 1>")
链式调用
import { type } from "arktype"

const  = type({
	name: "string",
	"age?": "number",
	isAdmin: "boolean"
})

// hover me!
const  = .pick("name", "age")

已调用

import { type } from "arktype"

const  = type.keywords.Exclude("boolean", "false")

HKT

我们的新泛型使用了一种新方法构建,该方法将任意外部类型作为原生 ArkType 泛型集成!这为否则不可能的外部集成打开了大量可能性。作为预览,以下是 Partial 的内部实现:

import { generic, Hkt } from "arktype"

const  = generic(["T", "object"])(
	args => args.T.partial(),
	class PartialHkt extends Hkt<[object]> {
		declare body: <this[0]>
	}
)

递归和循环泛型目前尚不可用,将很快添加。

有关更多使用示例,请查看泛型的单元测试 此处

外部

包装 Type 的最基本模式如下所示:

const  = <t extends string>(of: type.Any<t>) =>
	({
		box: of
	})

// @ts-expect-error
(("number"))

// Type<{ box: string }>
const  = (("string"))

对于更深入的集成,您可能希望直接解析定义:

const  = <const def>(
	of: type.<def>
): type.<{ of: def }> =>
	type.raw({
		box: of
	}) as never

// Type<{ box: string }>
const  = ("string")

在这种集成方面,天空才是极限,但请注意——TypeScript 泛型 notoriously 难以处理,如果您不习惯的话,您可能会发现像这样的 API 难以编写

On this page