Skip to main content

如何编写自己的类型提供程序

如何编写自己的类型提供程序

¥How to write your own type provider

实现自定义 类型提供者 时要记住的事项:

¥Things to keep in mind when implementing a custom type provider:

类型逆变

¥Type Contravariance

虽然详尽的类型缩小检查通常依赖于 never 来表示无法访问的状态,但类型提供程序接口的减少应该只到 unknown

¥Whereas exhaustive type narrowing checks normally rely on never to represent an unreachable state, reduction in type provider interfaces should only be done up to unknown.

原因是 FastifyInstance 的某些方法在 TypeProvider 上是逆变的,这可能导致 TypeScript 出现可分配性问题,除非自定义类型提供程序接口可以用 FastifyTypeProviderDefault 替代。

¥The reasoning is that certain methods of FastifyInstance are contravariant on TypeProvider, which can lead to TypeScript surfacing assignability issues unless the custom type provider interface is substitutable with FastifyTypeProviderDefault.

例如,FastifyTypeProviderDefault 将不能分配给以下内容:

¥For example, FastifyTypeProviderDefault will not be assignable to the following:

export interface NotSubstitutableTypeProvider extends FastifyTypeProvider {
// bad, nothing is assignable to `never` (except for itself)
validator: this['schema'] extends /** custom check here**/ ? /** narrowed type here **/ : never;
serializer: this['schema'] extends /** custom check here**/ ? /** narrowed type here **/ : never;
}

除非改为:

¥Unless changed to:

export interface SubstitutableTypeProvider extends FastifyTypeProvider {
// good, anything can be assigned to `unknown`
validator: this['schema'] extends /** custom check here**/ ? /** narrowed type here **/ : unknown;
serializer: this['schema'] extends /** custom check here**/ ? /** narrowed type here **/ : unknown;
}