3 个回答

你的reverse函数可能返回undefined, 所以不符合number|string的类型约束。

function reverse(x): number|string {
  if (xx) {
    return xxx // 返回number类型
  } else if (xxx) {
    return xxx // 返回string类型
  }
  // 这里隐式返回undefined类型
}

不复杂,直接看图

clipboard.png

ts会自动类型推导,阁下不必担心

function reverse(x: string): string
function reverse(x: number): number

function reverse(x: number | string): number | string {
  if (typeof x === 'number') {
    return Number(
      x
        .toString()
        .split('')
        .reverse()
        .join('')
    )
  } else if (typeof x === 'string') {
    return x
      .split('')
      .reverse()
      .join('')
  } else {
    return 6
  }
}

else if 后边应该还需要加上else,或者 if else ,未加else报缺少返回值

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进