|
| 1 | +# Section 6.2: Function as a parameter |
| 2 | + |
| 3 | +### Suppose we want to receive a function as a parameter, we can do it like this: |
| 4 | +```ts |
| 5 | +function foo(otherFunc: Function): void { |
| 6 | + ... |
| 7 | +} |
| 8 | +``` |
| 9 | + |
| 10 | +### If we want to receive a constructor as a parameter: |
| 11 | +```ts |
| 12 | +function foo(constructorFunc: { new() }) { |
| 13 | + new constructorFunc(); |
| 14 | +} |
| 15 | + |
| 16 | +function foo(constructorWithParamsFunc: { new(num: number) }) { |
| 17 | + new constructorWithParamsFunc(1); |
| 18 | +} |
| 19 | +``` |
| 20 | + |
| 21 | +### Or to make it easier to read we can define an interface describing the constructor: |
| 22 | +```ts |
| 23 | +interface IConstructor { |
| 24 | + new(); |
| 25 | +} |
| 26 | + |
| 27 | +function foo(contructorFunc: IConstructor) { |
| 28 | + new constructorFunc(); |
| 29 | +} |
| 30 | +``` |
| 31 | +### Or with parameters: |
| 32 | +```ts |
| 33 | +interface INumberConstructor { |
| 34 | + new(num: number); |
| 35 | +} |
| 36 | + |
| 37 | +function foo(contructorFunc: INumberConstructor) { |
| 38 | + new contructorFunc(1); |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +### Even with generics: |
| 43 | +```ts |
| 44 | +interface ITConstructor<T, U> { |
| 45 | + new(item: T): U; |
| 46 | +} |
| 47 | + |
| 48 | +function foo<T, U>(contructorFunc: ITConstructor<T, U>, item: T): U { |
| 49 | + return new contructorFunc(item); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +### If we want to receive a simple function and not a constructor it's almost the same: |
| 54 | +```ts |
| 55 | +function foo(func: { (): void }) { |
| 56 | + func(); |
| 57 | +} |
| 58 | + |
| 59 | +function foo(constructorWithParamsFunc: { (num: number): void }) { |
| 60 | + new constructorWithParamsFunc(1); |
| 61 | +} |
| 62 | +``` |
| 63 | +### Or to make it easier to read we can define an interface describing the function: |
| 64 | +```ts |
| 65 | +interface IFunction { |
| 66 | + (): void; |
| 67 | +} |
| 68 | + |
| 69 | +function foo(func: IFunction ) { |
| 70 | + func(); |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +### Or with parameters: |
| 75 | +```ts |
| 76 | +interface INumberFunction { |
| 77 | + (num: number): string; |
| 78 | +} |
| 79 | + |
| 80 | +function foo(func: INumberFunction ) { |
| 81 | + func(1); |
| 82 | +} |
| 83 | +``` |
| 84 | + |
| 85 | +### Even with generics: |
| 86 | +```ts |
| 87 | +interface ITFunc<T, U> { |
| 88 | + (item: T): U; |
| 89 | +} |
| 90 | + |
| 91 | +function foo<T, U>(contructorFunc: ITFunc<T, U>, item: T): U { |
| 92 | + return func(item); |
| 93 | +} |
| 94 | +``` |
0 commit comments