考虑这个使用 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
-- 而函数签名表明回调函数中的参数类型应与第一个参数的类型相同。
但是,代码编译后在运行时失败。
我缺少什么?
嗯,因为T
in baz: (T) => void
不是类型名称,而是参数名称。
当您修复语法以表示您想要的含义时,您会收到预期的错误:
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'.
诚然,很难发现这样的错误 - 我只有在将代码粘贴到时才看到它打字稿游乐场并打开--noImplicitAny
. (T)
立即突出显示Parameter 'T' implicitly has an 'any' type
。甚至那个错误也让人困惑了一会儿——等等——T
不是参数,而是类型 - ...!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)