为什么TypeScript不强制在回调中使用通用参数? [英] Why doesn't TypeScript enforce a generic parameter in callback?

查看:68
本文介绍了为什么TypeScript不强制在回调中使用通用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider this TypeScript code, compiled with 2.6.1:

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

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

我希望编译失败,因为使用string调用了函数foo,但是传递的回调函数使用的是string中不可用的方法-而函数签名表明:回调函数中的参数类型应与第一个参数的类型相同.

I would expect the compilation to fail, because the function foo is called with a string, but the passed callback function is using a method that is not available in string -- while the function signature indicates that type of argument in callback function should be the same as the type of the first parameter.

但是,代码会在运行时编译然后失败.

However, the code compiles and then fails in runtime.

我想念什么?

推荐答案

好吧,因为baz: (T) => void中的T不是类型名,而是参数名.

Well, because T in baz: (T) => void is not a type name, it's a parameter name.

当您将语法固定为您想要的含义时,您会得到预期的错误:

When you fix the syntax to mean what you want it to mean, you get the expected error:

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时,我才能看到它游乐场并打开--noImplicitAny. (T)立即以Parameter 'T' implicitly has an 'any' type突出显示.甚至那个错误也使人困惑不解-等待什么-T不是参数,它是类型-...!

Granted, it's really hard to spot errors like this one - I saw it only when I pasted your code into typescript playground and turned on --noImplicitAny. (T) immediately got highlighted with Parameter 'T' implicitly has an 'any' type. Even that error was puzzling for a moment - wait what - T is not a parameter, it's a type - ...!

这篇关于为什么TypeScript不强制在回调中使用通用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆