NestJs:为什么我们不';是否不使用DTO替换所有接口?

NestJs:为什么我们不';是否不使用DTO替换所有接口?,nestjs,Nestjs,我们能否使DTOs成为验证的真实来源,并在控制器和服务中使用它? 如果我已经有DTO,为什么我需要接口?如果你不想使用接口,就不需要接口。对于作为基本模型的DTO,我也不使用接口。也就是说,它们非常强大,所以我绝对不会阻止您使用它们,举个例子: interface ILogger { log(message: string) : Promise<void>; } class ConsoleLogger implements ILogger { log(message

我们能否使DTOs成为验证的真实来源,并在控制器和服务中使用它?
如果我已经有DTO,为什么我需要接口?

如果你不想使用接口,就不需要接口。对于作为基本模型的DTO,我也不使用接口。也就是说,它们非常强大,所以我绝对不会阻止您使用它们,举个例子:

interface ILogger {
    log(message: string) : Promise<void>;
}

class ConsoleLogger implements ILogger {
    log(message: string) : Promise<void> {
        return Promise.resolve(console.log(message));
    }
}

class DatabaseLogger implements ILogger {

    private dbConnection;

    constructor() {
        dbConnection = new DBConnection(); //Fake but it drives the point across 
    }

    async log(message: string) : Promise<void> {
        return await this.dbConnection.saveLog(message);
    }
}

class DoTheThing {

    private _logger: ILogger;

    //You can have nest inject the best logger for this situation and your code doesn't have to care
    //about the actual implementation :)
    constructor(logger: ILogger) {
        this._logger = logger;
    }

    async myMethod() {
        const tweetMessage = await sendTweet('...');
        this._logger.log(tweetMessage);
    }
}
接口ILogger{
日志(消息:字符串):承诺;
}
类ConsoleLogger实现ILogger{
日志(消息:string):承诺{
返回Promise.resolve(console.log(message));
}
}
类DatabaseLogger实现ILogger{
专用数据库连接;
构造函数(){
dbConnection=new dbConnection();//伪,但它会驱动点穿过
}
异步日志(消息:字符串):承诺{
返回wait this.dbConnection.saveLog(消息);
}
}
类DoTheThing{
私人记录器:ILogger;
//对于这种情况,您可以让nest注入最好的记录器,而您的代码不必在意
//关于实际实施:)
构造函数(记录器:ILogger){
这个。_logger=记录器;
}
异步myMethod(){
const tweetMessage=等待发送Tweet(“…”);
此._logger.log(tweetMessage);
}
}

您所说的“替换所有接口”是什么意思?