简体   繁体   English

TypeScript - 在 object 使用别名解构时指定类型

[英]TypeScript - specify type while object destructuring with alias

He everybody, I'm refactoring an NodeJS app to TypeScript.大家好,我正在将 NodeJS 应用程序重构为 TypeScript。 And I was making always object destructuring and also for the code block below I'm making and alias while object destructuring as you see.而且我一直在进行 object 解构,以及我正在制作的代码块和别名,而 object 如您所见。 And how can I specify type here?我怎样才能在这里指定类型?

const {length: isRegistered}  = await User.countDocuments({email: emailTo});

I would favour typing the return type of User.countDocuments({email: emailTo}) , which should be similar to Promise<{ length: number, ... }> .我倾向于输入User.countDocuments({email: emailTo})的返回类型,它应该类似于Promise<{ length: number, ... }> That way, TypeScript will infer the type of the destructed properties.这样,TypeScript 将推断出被破坏属性的类型。

Another way is to be more explicit by typing const {length: isRegistered}: {length: number} .另一种方法是通过键入更明确的const {length: isRegistered}: {length: number}

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

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