gpt4 book ai didi

typescript - 类型不可分配给类型 2322

转载 作者:行者123 更新时间:2023-12-05 04:35:42 24 4
gpt4 key购买 nike

为什么会引发以下问题:Type '(...args: T) => void' is not assignable to type 'Fn<T>'.(2322) :

type Fn<T extends unknown[]|unknown> = T extends unknown[] ? (...args: T)=>void : T

const func = <T extends unknown[]>()=>{
// why does this error and how does one resolve it?
// ideal Fn must handle cases outside of unknown[] including `any` and `unknown`
const fn : Fn<T> = (...args: T)=> console.log(args)
return fn
}

// some tests by me to try and understand what is going on:
type ValidFn1 = Fn<[value:number]>
type ValidFn2 = Fn<any>
type ValidFn3 = Fn<never>
type ValidFn4 = Fn<unknown>
type ValidFn5 = Fn<unknown[]>
type ValidFn6 = Fn<void>

const validFn1: ValidFn1 = (...args)=>console.log(args) // extends unknown[]
const validFn2: ValidFn2 = (...args:any)=>console.log(args) // any extends unknown[]
const validFn3: ValidFn3 = (...args:never)=>console.log(args) // never doesn't extend unknown[]
const validFn4: ValidFn4 = (...args:unknown)=>console.log(args) // unknown doesn't extend unknown[]
const validFn5: ValidFn5 = (...args:unknown[])=>console.log(args) // extends unknown[]
const validFn6: ValidFn6 = (...args:void)=>console.log(args) // void doesn't extend unknown[]

code

最佳答案

我相信这里发生的事情是以下事实的结合:(1) Typescript 不解析函数内部的条件类型,直到它被提供一个具体的实例化(参见 this SO answer)和 (2) 函数参数是逆变的(参见 this SO answer)。

所以,您在这里看到的基本上是 TS:

    const fn : Fn<T> = (...args: T)=> console.log(args)

和:

  • 解决 Fn<T>里面funcFn<unknown[]> ,即 (...args: unknown[]) => void ,(因为上面第 1 点)

  • 意识到 T右侧可能比 unknown[] 更窄(例如,number[])。

然后它认为,嗯,这可能行不通,因为,这可能是说,例如:

   const fn:(args:unknown[])=>void = (args:number[])=>console.log(args)

这是一个错误,因为 args 是逆变的(参见上面的第 2 点)。

如何解决?我认为解决第 1 点类别下问题的最简单方法是在函数上使用显式返回类型,然后在函数本身内部进行断言,例如:

const func = <T extends unknown[]>():Fn<T>=>{
const fn = (...args: T)=> console.log(args)
return fn as Fn<T>
}

关于typescript - 类型不可分配给类型 2322,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70982794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com