【问题标题】:Multiple types on arrow function parameters throwing ts error: ts(2322)箭头函数参数的多种类型抛出 ts 错误:ts(2322)
【发布时间】:2022-11-25 14:59:15
【问题描述】:

我在配置(对象)中传递箭头函数

const config:IConfig = {
    render: (item:string)=>item
}

我的参数项可以是string | string[]。所以我使用的界面是

interface IConfig  {
    render: (item:string|string[])=>string
}

但是使用上面的代码,render: (item:string)=>item 行会抛出一条错误消息

 Types of parameters 'item' and 'item' are incompatible.
    Type 'string | string[]' is not assignable to type 'string'.
      Type 'string[]' is not assignable to type 'string'.(2322)

我尝试了另一个工作正常的界面

interface IWorkingConfig {
    render: ((item:string )=>string) | ((item: string[])=>string)
}

唯一的区别是我传递的不是多个types参数,而是多个函数。

上述接口语法的问题

我需要复制整个函数只是为了改变参数的类型。这建立了很多重复的代码。

Runnable Code 用于上述 sn-ps

【问题讨论】:

  • 您的代码 sn-p 不包含任何代码
  • 还有你在哪里打电话给IConfig
  • 更新了网址。

标签: reactjs typescript types arrow-functions


【解决方案1】:

所以在实现中,你只返回一个字符串。但参数可以是字符串或字符串数​​组。所以你需要确保你返回的是一个字符串

const config:IConfig = {
    render: (item:string|string[])=>{

        if(typeof item === "string") return item
        return item[0] // should be a single string value
    }
}

Demo

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多