简体   繁体   中英

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.

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: 在此处输入图像描述

And when I press CTRL + BACKSPACE after 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

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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