Typescript: Cannot find name of imported function

Created on 16 Oct 2016  路  4Comments  路  Source: microsoft/TypeScript

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!

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.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

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tenry92 picture tenry92  路  146Comments

nitzantomer picture nitzantomer  路  135Comments

Gaelan picture Gaelan  路  231Comments

fdecampredon picture fdecampredon  路  358Comments

kimamula picture kimamula  路  147Comments