gpt4 book ai didi

typescript - 为什么 TypeScript 不在回调中强制使用通用参数?

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:30 25 4
gpt4 key购买 nike

考虑使用 2.6.1 编译的 TypeScript 代码:

function foo<T> (bar: T, baz: (T) => void) {
const test: T = bar;
baz(test);
}

const string: string = "a";
foo(string, num => num.parseInt());

我预计编译会失败,因为函数 foo 是用 string 调用的,但是传递的回调函数使用的方法在 string -- 而函数签名表明回调函数中的参数类型应该与第一个参数的类型相同。

但是,代码编译后在运行时失败。

我错过了什么?

最佳答案

嗯,因为 baz: (T) => void 中的 T 不是类型名称,而是参数名称。

当您修改语法以表达您想要表达的意思时,您会得到预期的错误:

function foo<T> (bar: T, baz: (t: T) => void) {
const test: T = bar;
baz(test);
}

const s: string = "a";
foo(s, num => num.parseInt());
// Property 'parseInt' does not exist on type 'string'.

当然,很难发现像这样的错误 - 只有当我将您的代码粘贴到 typescript playground 并打开 --noImplicitAny 时,我才看到它。 (T) 立即以 Parameter 'T' implicitly has an 'any' type 突出显示。甚至那个错误也让我困惑了片刻 - 等等 - T 不是参数,它是一个类型 - ...!

关于typescript - 为什么 TypeScript 不在回调中强制使用通用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443160/

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