是否有自动方法为命名空间中的所有接口创建区别性联合?

时间:2018-01-17 15:59:00

标签: typescript

我正在使用TypeScript(目前只有2.5,但如果需要,我可以更新到2.6)。

我有一个带有一些接口的命名空间:

public async Task<ViewModelBase> Search(int brokerDealerId, FilterParams filter)
    {
        var opts = new AdvisorSearchOptions
        {
            SearchKey = filter.SeachKey,
            AdvisorId = filter.AdvisorId,
            BranchId = filter.BranchId,
            City = filter.City,
            Skip = filter.Skip,
            Limit = filter.Limit,
            RadiusInMiles = filter.Limit,
            Longitude = filter.Longitude,
            Latitude = filter.Latitude
        };

        var searchResults = await _repository.SearchAdvisors(filter.CID.Value, opts);  // line 64 here

        if (searchResults.Count == 0 && Utils.IsZipCode(filter.SeachKey))
        {


        }

        //Some other code here

        return model;
    }

然后我为这些接口创建了一个有区别的联合:

export namespace Interfaces {
    export interface One {
        kind: "One"
    }

    export interface Two {
        kind: "Two"
    }

    export interface Three {
        kind: "Three"
    }
}

有没有办法动态执行此操作,以便每次添加界面时都不必手动更新受歧视的联合?

类似的东西:

export type KnownInterfaces = Interfaces.One | Interfaces.Two | Interfaces.Three;

1 个答案:

答案 0 :(得分:0)

这里不同的接近角度可能是保持一个映射而不是命名空间的类型:

export type Interfaces = {
  One: { kind: 'One' },
  Two: { kind: 'Two' },
  Three: { kind: 'Three' }
}
export type KnownInterfaces = Interfaces[keyof Interfaces]

您可以根据需要向Interfaces添加任意数量的属性,KnownInterfaces仍然是它们的联合。

这里的一个问题是你不能使用点表示法来引用各个接口:Interfaces.One将无法编译。您可以使用indexed-access表示法(也称为“查找类型”)来执行此操作,因此Interfaces['One']将起作用。我可以想象会变得烦人,所以你总是可以给它们带点符号:

export namespace Interfaces {
  export type One = Interfaces['One']
  export type Two = Interfaces['Two']
  export type Three = Interfaces['Three']
} 

但是现在你回到了在添加界面时在多个地方做某事的领域,所以你的里程可能会有所不同。也许只列出你需要简单名称的那些?

无论如何,希望有所帮助。祝你好运!