Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding declarations file manually (TypeScript)

I didn't find a declaration file for 'google-spreadsheet' so I'm trying to create one by myself:

in typings -> modules, I've added a new folder named "google-spreadsheet", and there I've added a new file named "index.d.ts" which has the following content:

export class GoogleSpreadsheet {

}

In the client file I have this:

import * as GoogleSpreadsheet from 'google-spreadsheet';

But 'google-spreadsheet' is marked with red, saying:

TS2307 Cannot find module 'google-spreadsheet'.

BTW I've NPM-installed 'google-spreadsheet' and it works JavaScriptly. Only the TypeScript bothers me here.

Any ideas how to solve that?

like image 229
Alon Avatar asked Mar 22 '17 22:03

Alon


People also ask

Where do I put TypeScript declaration?

All the type declarations that is added via DefinitelyTyped / @types will be saved under node_modules/@types/<package-name> folder. TypeScript will automatically detect these declaration files and infer the type from it.

How do I add a declaration file to a module?

Just create a file named typings. d. ts in the root directory of your project. Inside this file just add declare module <module_name> .

How do I include a file in TypeScript?

In the TypeScript file which is to be imported must include an export form and the main file where the class is imported must contain an import form, by which TypeScript can identify the file which is used.


2 Answers

From the root of your project:

  1. mkdir -p src/@types/google-spreadsheet - create a folder for your module's type declarations.
  2. echo "declare module 'google-spreadsheet';" > src/@types/google-spreadsheet/index.d.ts

Also, ensure your tsconfig is configured to include the @types folders using the typeRoots option.

{
  "compilerOptions": {
    "typeRoots": ["src/@types", "node_modules/@types"]
  }
}

Also, you might want to take a look at the documentation on declaration files.

like image 86
Federico Avatar answered Sep 27 '22 20:09

Federico


If you dont need to care about the typings inside this module you can only create a *.d.ts file and put the following content (e.g. create a typings.d.ts):

declare module 'google-spreadsheet';

To define the types inside the module you can change the above code to:

declare module 'google-spreadsheet' {
    // define the types...
}
like image 43
Diullei Avatar answered Sep 27 '22 19:09

Diullei