我想将lambda传递给函数,但需要一个带有单个参数的lambda。如果我将两个参数传递给lambda,TypeScript会根据需要抛出错误,但如果省略lambda中的任何参数则不会抱怨。如何让TypeScript要求传递单个参数lambda?
function foo(fn: (x) => any) { }
foo(() => "bla"); // Bad, but no error
foo((x) => "bla"); // Good, no error
foo((x, y) => "bla"); // Bad, with error
答案 0 :(得分:3)
从语义上讲, @Override
protected String doInBackground(String[] params) {
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Name", name ));
postParameters.add(new BasicNameValuePair("Email", email ));
postParameters.add(new BasicNameValuePair("Password", password));
String responseString = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://hitachipick.azurewebsites.net/SQLQuery.php");
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}
catch (Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
return"";
}
@Override
protected void onPostExecute(String message) {
//process message
}
}
和x => "bla"
完全相同。他们都完全忽略了第一个参数(以及其他所有参数)
通过要求() => "bla"
lambda,你基本上会说,“我想要一些我可以用一个参数调用的东西”,(x) => any
符合要求,() => "bla"
没有。
答案 1 :(得分:2)
这实际上是预期的行为,无论好坏。见https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-with-fewer-parameters-assignable-to-functions-that-take-more-parameters
不幸的是,我无法获得您想要的行为。