Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define import variable type

Tags:

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?

like image 650
mattnedrich Avatar asked Mar 23 '17 21:03

mattnedrich


People also ask

What are import variables?

User variables are specific to the SEER*Stat database for which they were created, but their definitions can be imported into other databases. Your process for doing so may differ depending on whether you have access to the original database.

What is import type?

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.

How do you import export type?

The exported type can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file. Here is an example of exporting a type from a file called another-file. ts .


1 Answers

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.

like image 155
Paarth Avatar answered Oct 27 '22 21:10

Paarth