作用是什么?"/>
@nestjs/common 中的类型是什么?它的作用是什么?
NestJS 在包@nestjs/common 中有接口类型。但是这两天我无法详细了解它的作用。你能帮忙吗?
举个例子,我拿这篇文章
.interface.ts
export interface Type<T = any> extends Function {
new (...args: any[]): T;
}
创建模板类的简短用法示例
import { Controller } from "@nestjs/common";
import { CoordinateService as S } from "@location/@coordinate/coordinate.service";
export interface Coordinate {
Id: string;
longitude: string;
latitude: string;
type: string;
}
export interface CoordinateId {
id: string;
}
@Controller()
export class CoordinateController extends BaseGrpcService<any, Coordinate, CoordinateId>(S) {}
import { Inject, Type, forwardRef } from "@nestjs/common";
import { GrpcMethod } from "@nestjs/microservices";
import { Metadata, ServerUnaryCall } from "@grpc/grpc-js";
import { Observable } from "rxjs";
export interface IProtoData {}
export interface IProtoDataId {
id: string;
}
export function BaseGrpcService<
T1 extends Type<Object>,
T2 extends IProtoData,
T3 extends IProtoDataId
>(classService: T1): any {
class BaseGrpcService extends Base implements IBaseGrpcService<T2, T3> {
constructor(
@Inject(forwardRef(() => classService))
private readonly baseService: IBaseService<T2, T2, T2>
) {
super();
}
@GrpcMethod(classService.name, "FindById")
async findById(request: T3, metarequest: Metadata): Promise<T2> {
return await this.baseService.findById(request?.id);
}
}
}
当我将字符串“T2 extends IProtoData”替换为“T2 extends Type”时,TS 向我发送了错误
错误 TS2344:类型“坐标”不满足约束“类型”。 类型“坐标”缺少类型“类型”的以下属性:应用、调用、绑定、原型和另外 5 个。
第二步
怎么了?
class ClassProtoData implements Coordinate {
Id: string;
longitude: string;
latitude: string;
type: string;
}
@Controller()
export class CoordinateController extends BaseGrpcService<any, ClassProtoData, CoordinateId>(S) {}
export function BaseGrpcService<
T1 extends Type<Object>,
T2 extends Type<IProtoData>,
T3 extends IProtoDataId
>(classService: T1): any {
}
因此,我对这个设计产生了误解。它有什么作用?
export interface Type<T = any> extends Function {
new (...args: any[]): T;
}
第三步:
是的,我知道我不应该使用它。我试图了解机制本身。这个机制有什么作用?
我正确理解 type.interface.ts 做了以下事情:
- 我们获取接口中描述的属性列表
- 继承函数对象
- 调用函数创建方法“new (...args: any[]): T;”
- 结果,我们得到的不是一个接口,而是一个 Javascript 函数的实例。
还是我错了?我对这段代码完全感到困惑。
回答如下:Type
是一个 Typescript 类型,表示我们在这里期待一个类 reference 而不是类实例。这在像 Nest 的 @Module()
的 imports
和 providers
数组这样的地方很有用,这样用户就可以传递类本身而不必实例化它。您的 T1
保留为 Type<>
是有意义的,因为您将类引用传递给 @Inject(forwardRef(() => T1))
应该 是类型引用。尽管如此,看起来您需要直接 T2
而不是 Type<T2>
这样您就知道返回该类类型的 instances(或满足该类型的对象)
更多推荐
@nestjs/common 中的类型是什么?它的作用是什么?
发布评论