我很难弄清楚在TypeScript中是否可以声明一个静态类型的函数数组.
例如,我可以这样做:
foo: (data:string) => void = function (data) {};
Run Code Online (Sandbox Code Playgroud)
但是如果我想让foo成为一个函数数组,它接受一个字符串而不返回任何内容,那我该怎么做呢?
foo: (data:string) => void [] = [];
Run Code Online (Sandbox Code Playgroud)
不起作用,因为TypeScript认为它是一个接受一个字符串并返回一个void数组的函数,它似乎不喜欢我试图将函数包装在括号中.
有任何想法吗?
答:感谢下面的mohamed,这是一个适用于TypeScript Playground的示例:
class whatever {
public foo: { (data: string): void; }[] = [];
dofoo() {
for (var i=0; i < this.foo.length; i++) {
this.foo[i]("test");
}
}
}
var d = new whatever();
d.foo.push(function(bar){alert(bar)})
d.foo.push(function(bar){alert(bar.length.toString())})
d.dofoo();
Run Code Online (Sandbox Code Playgroud)
moh*_*azy 74
您可以在语言规范部分3.5.5中找到它:
foo: { (data: string): void; } []
Run Code Online (Sandbox Code Playgroud)
Sar*_*ana 49
使用胖箭头键入函数数组的其他(更新,更可读)方法:
let foo: Array<(data: string) => void>;
let bar: ((data: string) => void)[];
Run Code Online (Sandbox Code Playgroud)
如果你想在 TypeScript 中声明一个可调用函数数组,你可以声明一个类型:
type Bar = (
(data: string) => void
);
Run Code Online (Sandbox Code Playgroud)
然后使用它:
const foo: Bar[] = [];
const fooFn = (data: string) => console.log(data);
foo.push(fooFn);
foo.forEach((fooFn: Bar) => fooFn("Something");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26538 次 |
| 最近记录: |