[英]How do I get vscode autocomplete after calling a function with a union as its return type in TypeScript?
How do I get proper editor autocomplete after calling a function that returns a union type?调用返回联合类型的函数后,如何获得正确的编辑器自动完成功能?
For example, in the code below, after calling getProperty<ColorfulOrCircle>()
(line 14), the variable b
should give show me what properties I can access, but that doesn't happen.例如,在下面的代码中,在调用
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
When I hover over b.color
, I get this error message:当我将鼠标悬停在
b.color
上时,我收到以下错误消息:
And when I press CTRL + BACKSPACE after b.
当我在
b.
, I receive only 'random' words. ,我只收到“随机”的话。
How should I type my function in order to have better intellisense?我应该如何键入我的函数以获得更好的智能感知?
When not specifying the generic type but letting typescript infer it, this works perfectly.当不指定泛型类型但让打字稿推断它时,这非常有效。 But as you can see, this function now requires a generic type in its declaration.
但正如您所见,这个函数现在需要在其声明中使用泛型类型。 If you want to have a function that can take a generic parameter like the original function in your question, check out the playground link where I included one at the bottom.
如果您想拥有一个可以像问题中的原始函数一样采用通用参数的函数,请查看我在底部包含的操场链接。
Code:代码:
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.