【问题标题】:Typescript - How to check destructured values instead using dot notation?Typescript - 如何检查解构值而不是使用点符号?
【发布时间】:2021-09-16 12:53:49
【问题描述】:

我有一个异步等待处理程序:

const asyncHandler = async <Type>(
  promise: Promise<Type>
): Promise<[Type, null] | [null, string]> => {
  try {
    const response = await promise
    return [response, null]
  } catch (error) {
    console.log(error)
    return [null, error]
  }
}

export default asyncHandler

这不会给我任何错误:

import asyncHandler from './async_handler'

interface Success {
  payload: string
}

interface MyError {
  payload: undefined
  error?: true
}

const fetchData = async (): Promise<Success | MyError> => {
  const fetchDataResponse = await asyncHandler<string>(
    new Promise((resolve) => {
      setTimeout(() => resolve('potato'), 200)
    })
  )

  if (fetchDataResponse[1]) return { payload: undefined, error: true }

  return { payload: fetchDataResponse[0] }
}

export default fetchData

但这会给出类型错误,因为期望响应是字符串或未定义但响应是字符串或空

import asyncHandler from './async_handler'

interface Success {
  payload: string
}

interface MyError {
  payload: undefined
  error?: true
}

const fetchData = async (): Promise<Success | MyError> => {
  const [response, error] = await asyncHandler<string>(
    new Promise((resolve) => {
      setTimeout(() => resolve('potato'), 200)
    })
  )

  if (error) return { payload: undefined, error: true }

  return { payload: response } // Type 'string | null' is not assignable to type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'.ts(2322)
}

export default fetchData

我知道响应不仅设置为字符串类型,因为这两个变量现在是独立的,但是有没有办法让第二个示例像第一个示例一样工作?

【问题讨论】:

  • 只是一个建议 - 您应该在 catch 块中使用 console.error() 而不是 console.log()
  • 哇,谢谢。我会用! :D

标签: javascript typescript async-await promise


【解决方案1】:

您需要检查fetchDataResponse[0] 是否有null

接下来正如您所描述的那样,您的接口MyErrorpayload 只能是undefined。对于接口Successpayload只能是string,但是你想返回response可以是string或者null

使payload 可选,您将实现您想要的

interface MyError {
  payload?: null
  error?: true
}

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多