typescript - 如何处理 typescript 中的不同类型?

标签 typescript

我试图了解 typescript 在这里是如何工作的。对于具有相似对象属性的对象,我能够处理。但像这样的事情怎么样?

形状具有不同的对象值。如何运行这个函数而不出错?

type Shape =
  | { kind: "circle"; radius: number }
  | { data: "square"; x: number };

function area(s: Shape) {
  if (s.kind === "circle") {
    return Math.PI * s.radius * s.radius;
  } else {
    return s.x * s.x;
  }
}

PS:这是一个损坏的代码。

最佳答案

圆形和方形都需要有 kind 属性。

下面应该可以工作。

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number };

function area(s: Shape) {
  if (s.kind === "circle") {
    return Math.PI * s.radius * s.radius;
  } else {
    return s.x * s.x;
  }
}

关于typescript - 如何处理 typescript 中的不同类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72641121/

相关文章:

typescript - 模拟器中的 Firebase 存储 : refFromUrl() expected a valid full URL

javascript - nodejs 异步等待流程无法正常工作

javascript - 如何告诉 Sonar 分析 *.ts 文件而不是 *.js 文件

node.js - 带有 Passport 本地 : Cannot use 'new' with an expression whose type lacks a call or construct signature 的 TypeScript

reactjs - TypeScript 2.6 -> Material-ui 1.0.0-beta.24 withStyles with React-router withRouter -> 类型中缺少属性 'classes'

typescript - 我可以使用部分实体通过 typeorm 进行保存吗?

typescript - 如何在 TypeScript 中使用 TimeSpan

Angular "Cannot read property ' 未定义的订阅'

javascript - 如何在 knockout.js 中实现带有属性的 TypeScript 类作为类?

typescript - 根据 typescript 中的构造函数参数重载类属性