如何在打字稿开关

时间:2017-12-20 22:39:24

标签: javascript typescript enums

我在一个文件中有这个:

export module  Utils {
    export enum DataSources {
        SharepointList = "SharepointList",
        JsonData = "JsonData"
    };
}

在另一个文件中我有这个:

import CustomerDAO from "./ICustomerDAO";
import SharepointListDAOFactory from "./SharepointListDAOFactory";
import JsonDAOFactory from "./JsonDAOFactory";
import {Utils} from "./DatasourcesEnum";


export default abstract class DAOFactory{

    public static SHAREPOINTLIST: number = 1;
    public static REMOTEJSON : number = 2;

    public abstract getCustomerDAO(): CustomerDAO;

    public  static getDAOFactory(whichFactory: Utils.DataSources): DAOFactory {   
      switch (whichFactory) {
        case whichFactory.SharepointList: 
            return new SharepointListDAOFactory();
        case whichFactory.JsonData: 
            return new JsonDAOFactory();      
        default  : 
            return null;
      }
    }
}

但是我得到了这些错误:

Property 'SharepointList' does not exist on type 'DataSources'.

1 个答案:

答案 0 :(得分:3)

我不太清楚你所获得的错误意味着什么。看来你的枚举似乎犯了错误。您在switch语句中使用已分配的值而不是枚举本身。

public  static getDAOFactory(whichFactory: Utils.DataSources): DAOFactory {   
   switch (whichFactory) {
     case Utils.DataSources.SharepointList: 
       return new SharepointListDAOFactory();
     case Utils.DataSources.JsonData: 
       return new JsonDAOFactory();      
     default  : 
       return null;
   }
 }

whichFactory标识符将具有一些反映在Utils.DataSources中的值,并且您希望将数据与枚举本身进行比较。该值本身不包含其他数据源枚举。