Home > other >  How do I get vscode autocomplete after calling a function with a union as its return type in TypeScr
How do I get vscode autocomplete after calling a function with a union as its return type in TypeScr

Time:07-01

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: enter image description here

And when I press CTRL BACKSPACE after b., I receive only 'random' words.

enter image description here

How should I type my function in order to have better intellisense?

CodePudding user response:

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

  • Related