TypeScript 用作参数
示例
假设我们想接收一个函数作为参数,我们可以这样做:
function foo(otherFunc: Function): void {
...
}如果要接收构造函数作为参数:
function foo(constructorFunc: { new() }) {
new constructorFunc();
}
function foo(constructorWithParamsFunc: { new(num: number) }) {
new constructorWithParamsFunc(1);
}为了使阅读更容易,我们可以定义一个描述构造函数的接口:
interface IConstructor {
new();
}
function foo(contructorFunc: IConstructor) {
new constructorFunc();
}或带有参数:
interface INumberConstructor {
new(num: number);
}
function foo(contructorFunc: INumberConstructor) {
new contructorFunc(1);
}即使使用泛型:
interface ITConstructor<T, U> {
new(item: T): U;
}
function foo<T, U>(contructorFunc: ITConstructor<T, U>, item: T): U {
return new contructorFunc(item);
}如果我们想接收一个简单的函数而不是一个构造函数,则几乎是相同的:
function foo(func: { (): void }) {
func();
}
function foo(constructorWithParamsFunc: { (num: number): void }) {
new constructorWithParamsFunc(1);
}为了使阅读更容易,我们可以定义一个描述函数的接口:
interface IFunction {
(): void;
}
function foo(func: IFunction ) {
func();
}或带有参数:
interface INumberFunction {
(num: number): string;
}
function foo(func: INumberFunction ) {
func(1);
}即使使用泛型:
interface ITFunc<T, U> {
(item: T): U;
}
function foo<T, U>(contructorFunc: ITFunc<T, U>, item: T): U {
return func(item);
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下