Reputation: 8072
I have noImplicitAny
set to true
for my TypeScript compiler. When I use an import like the following, it throws an error because I am not explicitly defining a type for the foo
variable:
import * as foo from "bar";
I am able to defined a type for foo
using the CommonJS require syntax:
const foo: FooType = require("bar");
Is there a way to define a type for foo
using the import * as ...
syntax?
Upvotes: 47
Views: 43875
Reputation: 10397
I believe you mean something like...
import * as foo: IFoo from "foo"
or
import foo : IFoo from "foo"
Is that accurate?
This was discussed, but ultimately decided against.
Instead, it was recommended that you declare module 'bar'
and give it your appropriate typing. Once that's done you will be able to import * as foo from "bar"
with proper typing.
See this issue for more details on the recommended approach
A potential example:
untyped.d.ts
declare module "bar" {
const foo:IFoo;
export = foo;
}
tsconfig.json
{
"compilerOptions": {
...
},
"include": [
"untyped.d.ts",
"src/**/*.ts",
"src/**/*.tsx"
]
}
the name "untyped.d.ts" has no real meaning here, I just personally use it as a catchall for the untyped modules in my personal projects. Feel free to name it whatever feels right to you.
p.s. you can also choose to use the files
array property rather than include
for this but I tend to not bother because files
doesn't respect the exclude
property which is confusing to some folks. See the docs for details.
Upvotes: 42