switch 语句中的 Typescript 特定类型

标签 typescript

我正在尝试编写一个函数,它在给定枚举值的情况下返回特定类型。 Typescript 无法识别 switch 和 if 语句中的属性。

interface A {
  a: string;
}

interface B {
  b: string;
}

enum DataType {
  a = 'a',
  b = 'b',
}

interface Type {
  [DataType.a]: A;
  [DataType.b]: B;
}

function test<T extends keyof Type>(type: T): Type[T] {
  switch (type) {
    case DataType.a:
      return {a: 'test'}; // <--- no error, but TS doesn't recognize the property
  }
}

使用 typescript 4.2.3

最佳答案

我不知道你是否可以接受,但是function overloads似乎工作。如果您决定采用此解决方案,则需要将 interface Type 替换为每种情况的特殊重载签名。

interface A {
  a: string;
}

interface B {
  b: string;
}

enum DataType {
  a = 'a',
  b = 'b',
}

function test(value: DataType.a): A;
function test(value: DataType.b): B; 
function test(value: DataType): A | B {
  switch (value) {
    case DataType.a:
      return {a: 'testA'};
    case DataType.b:
      return {b: 'testB'};
  }
}

TypeScript playground - live example

关于switch 语句中的 Typescript 特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66798083/

相关文章:

typescript - react 导航 + TypeScript 错误 : Type 'EventStackParams' does not satisfy the constraint 'Record<string, object | undefined>'

visual-studio - 如何使用生成的 *.d.ts 文件

typescript - EventSource 使用 TypeScript 命名事件

typescript - 有什么方法可以检查对象是否是 TypeScript 中的枚举类型?

javascript - 常量值作为数组元素给出错误

reactjs - 尝试将 D3 与 React 结合使用来创建条形图

javascript - typescript 错误地假定该属性是只读的

node.js - npm install --save-dev @ts2.0 标签名称无效 "@ts2.0"

class - Typescript 中类型为 'class' 的变量

typescript - mat-option需要2次点击事件来加载异步数据