在 TypeScript 中,如何声明一个接受字符串并返回字符串的函数数组? [英] In TypeScript how do I declare an array of functions that accept a string and return a string?

查看:32
本文介绍了在 TypeScript 中,如何声明一个接受字符串并返回字符串的函数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新 - 这个问题的上下文是 TypeScript 1.4 之前的.从那个版本开始,我的第一个猜测就得到了该语言的支持.请参阅答案的更新.

UPDATE - the context of this question was pre-TypeScript 1.4. Since that version, my first guess has been supported by the language. See the update to the answer.

我可以将 f 声明为一个接受字符串并返回字符串的函数:

I can declare f to be a function that accepts a string and returns a string:

var f : (string) => string

我可以声明 g 是一个字符串数组:

And I can declare g to be an array of string:

var g : string[]

如何将 h 声明为接受字符串并返回字符串的函数"的数组?

How can I declare h to be an array of "function that accepts a string and returns a string"?

我的第一个猜测:

var h : ((string) => string)[]

这似乎是一个语法错误.如果我去掉多余的括号,那么它就是一个从字符串到字符串数组的函数.

That seems to be a syntax error. If I take away the extra parentheses then it's a function from string to array of string.

推荐答案

我想通了.问题是函数类型文字的 => 本身只是语法糖,不想与 [] 组合.

I figured it out. The problem is that the => for a function type literal is itself merely syntactic sugar and doesn't want to compose with [].

正如规范所说:

形式为函数类型文字

(ParamList) => 返回类型

( ParamList ) => ReturnType

完全等同于对象类型文字

is exactly equivalent to the object type literal

{ ( ParamList ) : ReturnType }

{ ( ParamList ) : ReturnType }

所以我想要的是:

var h : { (s: string): string; }[]

完整示例:

var f : (string) => string

f = x => '(' + x + ')';

var h : { (s: string): string; }[]

h = [];

h.push(f);

更新:

这个变更集来看,在 1.4 中的类型声明中将允许使用括号,因此第一次猜测"这个问题也将是正确的:

Judging from this changeset parentheses will be allowed in type declarations in 1.4, so the "first guess" in the question will also be correct:

var h: ((string) => string)[]

进一步更新 1.4!

这篇关于在 TypeScript 中,如何声明一个接受字符串并返回字符串的函数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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