![](/img/trans.png)
[英]How do I get typescript to infer the return type of a function based on the return type on a function of its arguments
[英]How do I get vscode autocomplete after calling a function with a union as its return type in TypeScript?
调用返回联合类型的函数后,如何获得正确的编辑器自动完成功能?
例如,在下面的代码中,在调用getProperty<ColorfulOrCircle>()
(第 14 行)之后,变量b
应该告诉我我可以访问哪些属性,但这不会发生。
1. interface Colorful {
2. color: string;
3. }
4. interface Circle {
5. radius: number;
6. }
8. type ColorfulOrCircle = Colorful | Circle;
10. function getProperty<T>(cc: T): T {
11. return cc;
12. }
14. let b = getProperty<ColorfulOrCircle>({color: "red"})
15. b. ; // NO AUTOCOMPLETE
当我在b.
,我只收到“随机”的话。
我应该如何键入我的函数以获得更好的智能感知?
当不指定泛型类型但让打字稿推断它时,这非常有效。 但正如您所见,这个函数现在需要在其声明中使用泛型类型。 如果您想拥有一个可以像问题中的原始函数一样采用通用参数的函数,请查看我在底部包含的操场链接。
代码:
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
type ColorfulOrCircle = Colorful | Circle;
function getProperty<T extends ColorfulOrCircle>(cc: T) {
return cc;
}
let b = getProperty({ color: "red" })
b. ; // AUTOCOMPLETE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.