简体   繁体   English

打字稿泛型未返回正确的类型

[英]Typescript Generics not returning proper type

we use typescript generics in our project but it seems that when we use them as return type in the base class for example PromiseLike it gets PromiseLike<{}>. 我们在项目中使用了typescript泛型,但是当我们在基类中将它们用作返回类型时,例如PromiseLike,它将得到PromiseLike <{}>。

I have created a small app to reproduce the error: https://github.com/ssachtleben/typescript-generics-problem 我创建了一个小应用程序来重现该错误: https : //github.com/ssachtleben/typescript-generics-problem

Can somebody check it if its a mistake in our generics handling or a bug in typescript? 有人可以检查它是否是我们的泛型处理中的错误或打字稿中的错误吗?

Would be awesome. 太棒了。

Thanks, Sebastian 谢谢塞巴斯蒂安

The compiler isn't able to infer the type in your call to accountService.findOne, so it defaults to 'any'. 编译器无法在对accountService.findOne的调用中推断类型,因此默认情况下为“ any”。 You'll have to provide it yourself. 您必须自己提供。

 return new AccountService().findOne<Account>({}).then(account => account.username);

You should probably provide a method in your AccountService called findAccount that does this for you, so callers don't have to worry about it. 您可能应该在AccountService中提供一个名为findAccount的方法来为您执行此操作,因此调用者不必担心。

public findAccount(id: number): PromiseLike<Account> {    
    return this.findOne<Account>({ id: id }); //example
}

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

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