【问题标题】:Argument type URL is not assignable to parameter type string参数类型 URL 不可分配给参数类型字符串
【发布时间】:2021-02-03 07:01:48
【问题描述】:

我正在尝试使用 URL 类型执行 Axios 请求。但我收到错误Argument type URL is not assignable to parameter type string

import { Injectable } from '@nestjs/common'
import { NotificationsInterface } from '../interface/notifications.interface'
import { OS, UserType } from '../../global.constants'
const axios = require('axios').default

@Injectable()
export class NotificationsGateway implements NotificationsInterface {
  readonly urlDevices = new URL(
    'https://blablablabla.amazonaws.com/Prod/devices'
  )

  async saveDeviceAuthenticationInfos(
    userId: number,
    userType: UserType,
    deviceId: number,
    pushToken: string,
    operatingSystem: OS
  ): Promise<void> {
    const body = {
      userId,
      userType,
      deviceId,
      pushToken,
      operatingSystem,
    }

    await axios.post(this.urlDevices, body)
  }
}

我想如何让它工作?我有点想把它放回字符串,但我觉得这是一种回归。

【问题讨论】:

  • Axios 需要一个字符串,正如错误告诉你的那样 - 你可以传递 this.urlDevices.toString(),或者为 Axios 提供一个接受 URL 的外观(这将有其他好处),但是什么是目标是让它成为 URL 开始?
  • 好吧,我正在处理一个 URL,因此使用这种类型更严格是有意义的。这不是首先使用 typescript 而不是 vanilla JS 的原因吗?
  • 您可以使用.toString()将url字符串化:await axios.post(this.urlDevices.toString(), body)

标签: typescript url types axios


【解决方案1】:

就像错误所说的那样,您提供的是 URL,而应该是 string

如果您出于某些原因想继续使用URL 类型,可以执行以下操作:将this.urlDevices.toString() 作为axios.post() 方法的第一个参数。

或者,如果您不打算使用 URL 的静态方法,也可以将 urlDevices 输入为 string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多