TypeScript Intellisense对象值字符串

时间:2017-07-09 21:32:21

标签: javascript typescript interface webstorm

我有一个TypeScript .d.ts文件,我试图定义一个接受选项对象的函数。基于options对象的一个​​属性,我希望从第一个函数返回的对象中对对象值进行智能感知。这是一个例子:

carTypings.d.ts

interface LoadOptions {
    /** Type of Car */
    type: Type;
}

interface LoadOptions_Tesla {
    /** Type of Car */
    type: Type.TESLA;
}

interface LoadOptions_Chevy {
    /** Type of Car */
    type: Type.CHEVY;
}

interface GetStyleOptions {
    /** Model of car. */
    model: string;
}

interface GetStyleOptions_Tesla {
    /** Model of car. */
    model: 'Model S' | 'Model 3' | 'Model X';
}

interface GetStyleOptions_Chevy {
    /** Model of car. */
    model: 'Volt' | 'Bolt' | 'Malibu';
}

type Style = 'Sedan' | 'SUV' | 'Truck';

interface GenericCar {
    /** Returns the style of a car. */
    getStyle(options: GetStyleOptions): Style;
    /** The record type. */
    type: Type | string;
}

interface Tesla extends GenericCar {
    /** Returns the style of a car. */
    getStyle(options: GetStyleOptions_Tesla): Style;
}

interface Chevy extends GenericCar {
    /** Returns the style of a car. */
    getStyle(options: GetStyleOptions_Chevy): Style;
}

interface CarLoadFunction {
    (options: LoadOptions_Tesla): Tesla;
    (options: LoadOptions_Chevy): Chevy;
    (options: LoadOptions): GenericCar;
}

export const enum Type {
    TESLA = 1,
    CHEVY = 2,
    ITIALIAN = 3
}

export let load: CarLoadFunction;

cars.ts

import * as record from './carTypings'

let someItalianCar = record.load({ type: record.Type.ITIALIAN });
someItalianCar.getStyle({ model: 'Italian Model Z' }); //<— I don’t get an error here but intellisense is recommending me the Tesla models, which it should not.

let teslaRec = record.load({ type: record.Type.TESLA });
teslaRec.getStyle({ model: 'Model 3' }); //<— This works as expected

let chevyRec = record.load({ type: record.Type.CHEVY });
chevyRec.getStyle({ model: 'Bolt' }); //<—This also does not give me an error but intellisense recommended the Tesla models instead of the Chevy ones.

在我想要的cars.ts文件中,如果我加载CHEVY类型的汽车记录,当我拨打.getStyle时,模型的唯一选项是&#39; Volt ,'&#39;博尔特&#39;或者&#39; Malibu。'同样,如果我加载一辆没有特定定义的汽车(比如'someItalianCar'),我不应该得到任何智能感知。目前,无论何种类型,我都将特斯拉模型作为智能感知器。我认为这是由CarLoadFunction定义引起的,因为特斯拉选项是第一个被定义的选项,但我不知道其他任何编写方式。

我还应该注意,我使用IntelliJ的WebStorm作为我的IDE。我不知道其他IDE的TypeScript行为是否不同。

0 个答案:

没有答案