TypeScript Version: 2.0.3
Code
Foo.ts:
export default function Foo(): any {}
Bar.ts:
import Foo from './path/to/my/fn/Foo'
export default class Bar {
constructor(
private Foo: Foo, // Second Foo is underlined. Error: 'Cannot find name Foo.'
) {}
}
When using Foo as a type definition, it throws an error. Is this a intended behavior? Can you please refer me to the specification where is this discussed or help me with this? Thank you!
This is By Design. In order to use a function as type you have 2 options:
1. use typeof
export default class Bar {
constructor(
private foo: typeof Foo, // you will have to rename the property or the names will clash.
) {}
}
2. use interface
export interface Foo {
// this is function signature.
(): void;
// you can overload it and stuff:
(a: number): string;
}
// implementation:
export default (() => {...}) as Foo;
// and then:
import {Foo} from './path/to/my/fn/Foo'
export default class Bar {
constructor(
private Foo: Foo,
) {}
}
@alitaheri all of your advice is good and your solution works, but you lose the simplicity of the default import sugar needlessly.
I think a better solution, and one that preserves the structure of any code consuming foo.ts is
_foo.ts_
interface Foo {
(a: number): string;
(): void;
}
const Foo = ((a?: number) => {
if (a || a === 0) {
return a.toString();
}
}) as Foo;
export default Foo;
_bar.ts_
import Foo from './foo';
class Bar {
Foo: Foo;
}
Foo(); // call foo as a function
Didn't know you could do that O.o
Thanks a lot 馃憤 馃憤 馃憤
I just realized there in my example, I lost the correspondence between the type Foo and the function Foo within the module _foo_. I fixed the example.
Most helpful comment
@alitaheri all of your advice is good and your solution works, but you lose the simplicity of the default import sugar needlessly.
I think a better solution, and one that preserves the structure of any code consuming
foo.tsis_foo.ts_
_bar.ts_