【问题标题】:Why TypeScript forces me to return in unreachable code?为什么 TypeScript 强制我返回无法访问的代码?
【发布时间】:2022-06-21 10:41:45
【问题描述】:

我有这个代码:

import { Point, LineString } from 'geojson';

export function getIconPoint(geometrie: Point | LineString): Point {
  if (geometrie.type === 'Point') {
    return geometrie;
  }

  if (geometrie.type === 'LineString') {
    return {
      type: 'Point',
      coordinates: geometrie.coordinates[0],
    }
  }

  // unreachable
}

在两个if 语句之后,代码被认为是不可访问的,因为Point 和LineString 是基于它们的type 字段的可区分接口。仍然 TypeScript 不高兴并要求我返回一些东西,但我不想添加除 Point 之外的任何东西作为返回值类型:

函数缺少结束返回语句并且返回类型没有 包括“未定义”

如何以干净的方式解决此问题?

TypeScript playground

【问题讨论】:

  • 没有什么能真正确保type 可以仅是这两个值。最后的代码并不是真的无法访问,因此您必须从中返回一些内容。
  • 它与开关一起使用:tsplay.dev/mL4Zkm
  • @jonrsharpe 确实很有趣,很想知道为什么这种控制流结构的行为不同。
  • @Alejandro 参数是Point 或LineString,所以geometrie.type 是"Point" | "LineString"。
  • @GuerricP if else 之所以有效,是因为它详尽没有任何类型信息; switch 不是。但是 if else if 不起作用 即使编译器知道 'Point' 是 geometrie.type 的唯一剩余值。所以我猜这只是控制流分析的一个限制。

标签: typescript


【解决方案1】:

在这种情况下,为什么不直接省略else?
如果你只有两个选择,那就是……

import { Point, LineString } from 'geojson';

export function getIconPoint(geometrie: Point | LineString): Point {
  if (geometrie.type === 'Point') {
    return geometrie;
  }

  return {
    type: 'Point',
    coordinates: geometrie.coordinates[0],
  }
}

顺便说一句,如果您有更多选择,请同上。只需省略最后一个条件。
TypeScript 不应该在这样写的时候抱怨。

显然,为了使它更好,我们可能更愿意使用 exhaustive type-checking 函数。

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2014-02-25
    • 1970-01-01
    • 2021-10-06
    • 2020-07-09
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多