[英]How to define a generic anonymous function type in TypeScript?
[英]How to define result type of anonymous function?
我想在array.map(..)
中使用元组作为结果类型,并且我正在寻找一种不预先定义它们的类型的方法,因为我的函数通常很短并且导致只有两个组件的元组。
定义匿名 function 的结果类型的正确语法是什么?
// input
let list: string[] = [ "a", "abc" ]
// possible type definition
type Tuple = [string, number];
// verbose function definition
function hello(s: string): Tuple
{
return [s, s.length];
}
// different ways to use .map() with
// same results to show syntax options
let v0 = list.map( s => hello( s ) );
let v1 = list.map( (s: string): Tuple => hello(s) );
let v2 = list.map( (s: string): Tuple =>
{
return [s, s.length]
});
let v3 = list.map( (s: string): [string, number] =>
{
return [s, s.length]
});
let v4 = list.map( (s): [string, number] =>
{
return [s, s.length]
});
let v5 = list.map( (s): [string, number] => [s, s.length] );
在线尝试,立即错误突出显示www.typescriptlang.org
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.