类型推断如何与TypeScript中的联合类型+条件类型和泛型一起使用?

问题描述

我正在用Angular开发游戏,并试图将演示与游戏逻辑脱钩。为了实现这一点,我建立了一个单独的UiController服务来处理用户交互和演示。每当需要显示某些内容或需要执行用户操作时,与游戏逻辑相关的服务就会向UiController发出请求。

为了尽可能整洁地实现此目的,我试图抽象出与UiController进行交互的接口。一种常见的互动方式是 choice (选择),当玩家必须在同一类别的不同选项中选择一种时。该交互由requestChoice()的{​​{1}}方法处理,该方法需要一个UiController类型的参数。由于选择的类别很多,因此该类型必须包含所有这些类别,并且该方法必须知道如何处理所有这些类别。

例如,可能要求用户选择怪物或英雄。我使用文字类型来引用选项中的选项:

ChoiceRequest

构建type HeroType = 'warrior' | 'rogue' | 'mage'; type MonsterType = 'goblin' | 'demon' | 'dragon'; 第一种方法是使用泛型和条件类型:

ChoiceRequest

当构建这样的选择请求时,这被证明是有用的,因为type ChoiceType = 'hero' | 'monster'; type OptionsSet<T extends ChoiceType> = T extends 'hero' ? HeroType[] : T extends 'monster' ? MonsterType[] : never; interface ChoiceRequest<T extends ChoiceType> { player: Player; type: T; options: OptionsSet<T>; } type中的项目的值可以正确预测或拒绝:

options

但是,当我尝试使const request: ChoiceRequest<'monster'> = { player: player2,type: 'monster',// OK,any other value wrong options: ['demon','goblin'] // OK,any value not included in MonsterType wrong. } 方法处理不同情况时,类型推断无法按预期工作:

requestChoice()

(*)类型'number'与类型'T'不具有可比性。 'T'可能是 用任意类型实例化,该类型可能与 “数字”。

我以前曾多次遇到此问题,但我不完全理解为什么会发生这种情况。我认为这与条件类型有关,因此我尝试了一种不太优雅的第二种方法

public requestChoice<T extends ChoiceType>(request: ChoiceRequest<T>) {
  switch (request.type) {
    case 'a':             // OK,but should complain since values can only be 'hero' or 'monster'
      ...
    case 1:               // Here it complains,see below (*)
      ...
    ...
  }
}

但是,这种方法与第一种方法完全一样。

使这项工作按预期进行的唯一方法第三种方法,将interface ChoiceMap { hero: HeroType[]; monster: MonsterType[]; } type ChoiceType = keyof ChoiceMap; interface ChoiceRequest<T extends ChoiceType> { player: Player; type: T; options: ChoiceMap[T]; } 显式地构建为标记联合,而没有泛型或条件类型:

ChoiceRequest

问题:为什么第三种方法有效而前两种方法无效?我缺少类型推断的工作原理吗?在这种情况下还有其他模式可以实现我所需要的吗?

解决方法

如果在返回类型中不需要T,则可能是一个非常简单的解决方法:

function requestChoice(request: ChoiceRequest<ChoiceType>) {
  switch (request.type) {
    case 'a':             // Type '"a"' is not comparable to type ChoiceType
    case 1:               // Type '1' is not comparable to type ChoiceType
    case "hero": // fine
  }
}