gpt4 book ai didi

typescript - 这个 `Type ' any[ ]' is not assignable to type ' [number]` TypeScript 错误的原因是什么?

转载 作者:行者123 更新时间:2023-12-05 04:38:58 34 4
gpt4 key购买 nike

interface Fn {
(data: Data): void
}

interface Data<Value = any, Deps extends any[] = [...any]> {
value: Value
list: Deps
}

function fn(data: Data<string, [number]>): void {
console.log(data)
}

const foo: Fn[] = [fn]
console.log(foo)

tested against the TypeScript Compiler此代码会引发错误,因为 Type 'any[]' is not assignable to type '[number]'

我的直觉是定义的 fn 被分配给通用的 Data 值,但错误表明分配方向相反。这是 TypeScript 编译器的错误或限制吗?或者我应该如何考虑这个以获得更好的直觉?

最佳答案

同一问题的大大简化示例:

type FruitSmasher = (fruit: 'apple' | 'orange' | 'pear') => void
const appleSmasher: FruitSmasher = (apple: 'apple') => undefined
// Type '"apple" | "orange" | "pear"' is not assignable to type '"apple"'.

appleSmasher('orange') // this is bad.

appleSmasher 不能分配给 FruitSmasher 类型,因为水果粉碎机可以粉碎任何水果,但 appleSmasher 只知道如何粉碎苹果。因此,您不能像对待 FruitSmasher 一样对待 appleSmasher

Playground


这与您的直觉相反,因为此处的 Fn 需要使用 any[] 作为 Deps 进行调用。这意味着 [123]['asd', 123][] 都需要被允许作为 Deps 以便被视为与 Fn 相同的类型。

但是,fn 实际上要求Deps[number],这意味着any[] 不是'我不会去上类。

所以根据Fn的类型。这应该是有效的:

function fn(data: Data<string, [number]>): void {
console.log(data.list[0].toString()) // this will crash
}

const foo: Fn[] = [fn] // ignore this very valid type error for now

// Valid for type `Fn`, catastrophic for function `fn`.
foo[0]({ value: 123, list: [] })

但是 fnDeps 现在不满意。 data.list[0] 会返回 undefined,然后会在 .toString() 上崩溃。

是的,[number] 可以分配给 any[]。但是当函数的参数被声明为 any[] 时,任何比这更具体的东西都会破坏它,因为不能保证该函数是它需要的类型.

关于typescript - 这个 `Type ' any[ ]' is not assignable to type ' [number]` TypeScript 错误的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70498688/

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