在打字稿我怎么申报接受一个字符串并返回一个字符串函数数组? [英] In TypeScript how do I declare an array of functions that accept a string and return a string?
问题描述
我可以声明˚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.
推荐答案
我想通了。问题是,在 =>
一个函数类型文本本身只是语法糖,并且不希望与 [] $撰写C $ C>。
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):返回类型}
{ ( 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!
这篇关于在打字稿我怎么申报接受一个字符串并返回一个字符串函数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!