【问题标题】:When calling a callback function with a conditional type, typescript requires passing a parameter with an intersection of types使用条件类型调用回调函数时,打字稿需要传递具有类型交集的参数
【发布时间】:2023-01-30 23:56:35
【问题描述】:

有一个函数接受一组特定的参数。特别是,回调函数将一个对象或一组对象作为参数,该对象或对象数组依赖于另一个 isArray 参数。

我想上瘾。

type Option = {
  name: string
  value: string
> }

type FunctionProps<IsArray extends boolean | undefined> = {
  isArray?: IsArray
  callback: IsArray extends false
>     ? (options: Option) => void
>     : (options: option[]) => void
> }

const func = <T extends boolean | undefined = false>({isArray, callback}: FunctionProps<T>) => {
  const options: Option[] = /* */
  const currentOption: Option = /* */

  if (isArray) {
    callback(options)  // Argument of type 'Option[]' is not assignable to parameter of type 'Option & Option[]'.
  else {
    callback(currentOption)  // Argument of type 'Option' is not assignable to parameter of type 'Option & Option[]'.
>   }
> }

调用 func 时,一切正常,但在 func 内部调用回调时,typescript 想要获取类型 Option &amp; Option[] 的交集作为参数。我可以在调用callback(value as Option &amp; Option[])的时候显式指定类型,但是这样就很难理解了,也不清楚里面到底发生了什么。 是不是可以在里面把类型定义的更清楚一些?附言如果我这样声明函数类型,什么都不会改变

type FunctionProps = {
  isArray: false
  callback: (options: Option) => void
} | {
  isArray: true
  callback: (options: Option[]) => void
}

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    基于isArray 缩小callback 需要有区别的联合 FunctionProps 不是有区别的联合,因此 TS 将无法遵循属性类型之间的关系。

    在这种情况下,更好的选择是使 FunctionProps 成为可区分的联合并且不使用类型参数:

    type FunctionProps = {
        isArray?: false
        callback: (options: Option) => void
    } | {
        isArray: true
        callback: (options: Option[]) => void
    }
    
    const func =({ isArray, callback }: FunctionProps) => {
        const options: Option[] = null!
        const currentOption: Option = null!;
    
        if (isArray) {
            callback(options)  
        } else {
            callback(currentOption)  
        }
    }
    

    Playground Link

    【讨论】:

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