[BUG] Intellisense/Autocomplete Inaccurate On TypeScript String Literals
I have run into a situation where Webstorm's autocomplete, on a Typescript file, recommends the wrong types for string literals that are values of an object. Below is an example of the bug.
const enum Type {
TESLA,
CHEVY,
ITIALIAN
}
interface GenericCar {
/** Returns the style of a car. */
getStyle(options: { model: string }): string;
}
interface Tesla extends GenericCar {
/** Returns the style of a car. */
getStyle(options: { model: 'Model X' | 'Model S' | 'Model 3' }): string;
}
interface Chevy extends GenericCar {
/** Returns the style of a car. */
getStyle(options: { model: 'Volt' | 'Bolt' | 'Malibu' }): string;
}
interface carLoadFunction {
(options: { type: Type.TESLA }): Tesla;
(options: { type: Type.CHEVY }): Chevy;
(options: { type: Type }): GenericCar;
}
let carLoader: carLoadFunction;
let chevyCar = carLoader({ type: Type.CHEVY });
chevyCar.getStyle({ model: 'Model 3' }); //<--- This shows a type error that 'Model 3' is not one of the Chevy models but autocomplete recommended it anyway!
let teslaCar = carLoader({ type: Type.TESLA });
teslaCar.getStyle({ model: 'Model 3' }); //<--- This is what autocomplete recommended and is correct
let genericCar = carLoader({ type: Type.ITIALIAN });
genericCar.getStyle({ model: 'Model 3' }); //<--- This is what autocomplete recommended even though any string could be accepted here
As you can see Webstorm autocomplete has unexpected behavior for the Chevy and the Generic car instances, and just uses the Tesla models in all three cases. The problem corrects itself if you switch out the enums for string literals, however. Like so:
interface carLoadFunction {
(options: { type: 'Tesla' }): Tesla;
(options: { type: 'Chevy' }): Chevy;
(options: { type: string }): GenericCar;
}
let carLoader: carLoadFunction;
let chevyCar = carLoader({ type: 'Chevy' });
chevyCar.getStyle({ model: 'Bolt' }); //<--- Correct autocomplete
let teslaCar = carLoader({ type: 'Tesla' });
teslaCar.getStyle({ model: 'Model 3' }); //<--- Correct autocomplete
let genericCar = carLoader({ type: 'Italian' });
genericCar.getStyle({ model: '' }); //<--- Correct autocomplete
So I believe the issue is somehow tied to how the enums are interpreted by Webstorm. I have tested this in other IDE's (mainly VS) which were able to present the correct autocomplete options in either scenario. Hopefully this is the correct place to post this so that it is addressed.
Please sign in to leave a comment.
thanks for detailed sample, reproduced; please follow https://youtrack.jetbrains.com/issue/WEB-27829 for updates