1
votes

I'm writing an Angular2 app, and in it I'm using an external NPM package that has its own typings file. The problem is that the typings file is outdated - there are functions in the package that are available, but aren't declared in the typings file.

So I want to figure out:

  1. How to define my own typings file and get it recognized by Angular2
  2. How to extend an existing interface typing with new members
  3. How to write the typing in the correct way

I've tried Googling, but couldn't figure out an answer to any of those 3 questions. I mean I created a .d.ts file, but I don't know how to get Angular2 to recognize it, and also I don't know the correct syntax.

declare namespace ContentfulClientAPI {
    export interface ContentfulClientApi {
        parseEntries(data: any): any;
    }
}

I'm specifically trying to extend ContenfulClientAPI defined here:

1

1 Answers

0
votes

I got it to work in editor, but when running 'ng build', angular-cli for some reason doesn't find the new function still. Turns out angular-cli only recognizes typings in the './src/typings.d.ts' file for some reason, so if you're using angular-cli, add the path to it in 'typeRoots' and put the typings in that file.

  1. First, for the editor and compiler to recognize .d.ts files, you need to edit the "typeRoots" property in the 'tsconfig.json' file. The property specifies where should the compiler (and editor) look for typings. By default it only looks in "node_modules/@types", but you can additionally add "./typings", for example.
  2. In the new location you specified, create a new typings file, for example 'contentful.d.ts' and inside create the typing. Follow these to figure out the correct syntax: https://www.typescriptlang.org/docs/handbook/declaration-files/templates.html

For me, the final typings file looks like this:

import * as contentful from 'contentful';

declare module 'contentful' {
    export interface ContentfulClientApi {
        parseEntries(data: any): any;
    }
}