简体   繁体   English

您可以将带有装饰器的 Typescript 类导出为普通类(没有装饰器)吗?

[英]Can you export a Typescript class with decorators as a plain class (without decorators)?

Lets say I have a class like this:假设我有一个这样的课程:

import { Injectable } from '@nestjs/common';
import { IsString } from 'class-validator';
import { prop } from '@typegoose/typegoose';

@Injectable()
export class Human
{
    @prop({ unique: true })
    @IsString()
    readonly name: string;
}

The question is: can I export this class so that the receiving end gets it without the decorators, like this:问题是:我可以导出这个类,以便接收端在没有装饰器的情况下获取它,像这样:

class Human
{
    readonly name: string;
}

I want to export the class (which has other dependencies for the decorators) so that the file importing it does not require the dependencies used for those decorators, such as nestjs, class-validator, and typegoose.我想导出该类(它具有装饰器的其他依赖项),以便导入它的文件不需要用于这些装饰器的依赖项,例如 nestjs、class-validator 和 typegoose。

I'm trying to NOT write out "readonly name: string;"我试图不写出“只读名称:字符串;” more than once.不止一次。

So I figured it out, in part thanks to zett42.所以我想通了,部分归功于 zett42。

You can define a type in typescript, so if you just make a type that is equal to the class, then export that type, you will effectively be exporting that class definition without decorators.您可以在打字稿中定义一个type ,因此如果您只创建一个与该类相等的类型,然后导出该类型,您将有效地导出该类定义而无需装饰器。 You can also do it with interfaces , but types seem to be cleaner.您也可以使用interfaces来做到这一点,但类型似乎更清晰。 However I'm not sure if types behave the same as interfaces, time to read the Typescript documentation!但是我不确定类型的行为是否与接口相同,是时候阅读 Typescript 文档了!

With types:有类型:

export type THuman = Human;

With interfaces:带接口:

export interface IHuman extends Human {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM