我通过显式设置属性来为我的对象设置全局命名空间window.
window.MyNamespace = window.MyNamespace || {};
Run Code Online (Sandbox Code Playgroud)
TypeScript强调MyNamespace并抱怨:
属性'MyNamespace'在'window'类型的值上不存在任何"
我可以通过声明MyNamespace为环境变量并删除window显式来使代码工作,但我不想这样做.
declare var MyNamespace: any;
MyNamespace = MyNamespace || {};
Run Code Online (Sandbox Code Playgroud)
我怎样才能window留在那里让TypeScript开心?
作为旁注,我发现TypeScript抱怨特别有趣,因为它告诉我这种window类型any绝对可以包含任何东西.
我正在尝试使用speechSynthesis http://blog.teamtreehouse.com/getting-started-speech-synthesis-api
首先,我使用界面扩展了窗口:
window.interface.ts
export interface IWindow extends Window {
webkitSpeechRecognition: any;
speechSynthesis: any;
}
Run Code Online (Sandbox Code Playgroud)
接下来我做了一个窗口服务:
window.service.ts
import { Injectable } from '@angular/core';
import { IWindow } from '../interfaces/window-interface';
function _window() : IWindow {
return window;
}
@Injectable()
export class WindowService {
get nativeWindow() : any {
return _window();
}
}
Run Code Online (Sandbox Code Playgroud)
现在在组件中,我正在尝试实现它......没有成功..
app.component
import { Component, OnInit, ViewChild } from '@angular/core';
import { WindowService } from '../../providers/window.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['.app.component.scss']
})
export class AppComponent implements OnInit …Run Code Online (Sandbox Code Playgroud)