angulartypescriptyoutube-apiyoutube-iframe-api

youtube.d.ts File for the youtube-iframe-api to use in Angular 2 needed


I try to use the youtube iframe api for showing and controling video snippets with a smooth angular2 integration. And respecting the type concept of typescript is important to the webpack compiler and me :).

The quick setup of my tests:

use @angular/cli (Version 1.0.0-beta.32.3) to setup and install the ng2-youtube-player and then two small adjustments:

ng new test002
cd test002
npm install ng2-youtube-player --save-dev

The app.module was extended according to ng2-youtube-player, but in the app.component I had a small correction and an error:

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',// app renamed to app-root
    template: `
        <youtube-player
      [videoId]="id"
      (ready)="savePlayer($event)"
      (change)="onStateChange($event)"
    ></youtube-player>
    `
})
export class AppComponent {
  player: YT.Player;// Error: Cannot find namespace 'YT'
  private id: string = 'qDuKsiwS5xw';

    savePlayer (player) {
    this.player = player;
    console.log('player instance', player)
    }
  onStateChange(event){
    console.log('player state', event.data);
  }
}

For the error I faked the namespace with a youtube.d.ts file:

// dummy namespace...
export as namespace YT;

export interface Player {
    name: string;
    length: number;
    extras?: string[];
}

Now using ng serve the webpack is compiling without error, even if there is YT unknown within the ng2-youtube-player package.

My question after intensive search on the internet: Can someone may provide a correct .d.ts file or tell me how to find out?


Solution

  • This installs the TypeScript types for the YouTube iframe:

    Using Yarn:

    yarn add @types/youtube
    

    Or NPM:

    npm install @types/youtube
    

    As @TaeKwonJoe points out below, with @types/youtube installed, add the following to your project tsconfig.json under compilerOptions:

    "typeRoots": [
        "node_modules/@types"
    ],
    "types": [ "youtube" ]