我正在从谷歌
创建webgl-utils.js的d.ts文件我遇到的问题是全局对象中的方法是“猴子修补”的最后一行(我认为这是正确的术语)
问题专栏如下:
/**
* Provides requestAnimationFrame in a cross browser way.
*/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000/60);
};
})();
如何在我的打字稿文件中声明这一点,以便在使用该函数时不会出现编译错误:
function tick()
{
requestAnimFrame(tick);
drawScene();
}
我现在尝试过:
interface window
{
requestAnimFrame(): any;
}
但这并没有消除错误:
The name 'requestAnimFrame' does not exist in the current scope
答案 0 :(得分:8)
您正朝着正确的方向前进,但您需要定义所有变体:
interface Window {
requestAnimFrame(callback: any, element?: any): void;
webkitRequestAnimationFrame(callback: any, element?: any): void;
mozRequestAnimationFrame(callback: any, element?: any): void;
oRequestAnimationFrame(callback: any, element?: any): void;
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element?) {
window.setTimeout(callback, 1000/60);
};
})();
function tick() {
window.requestAnimFrame(tick);
}
答案 1 :(得分:3)
确保接口名称以大写“W”而不是“w”开头
interface Window {
requestAnimFrame():any;
}
在主叫代码中使用window.requestAnimFrame();
。希望这能解决你的问题
答案 2 :(得分:1)
declare var wnd: {
requestAnimationFrame: any;
webkitRequestAnimationFrame: any;
mozRequestAnimationFrame: any;
oRequestAnimationFrame: any;
msRequestAnimationFrame: any;
}
var wnd = window;
export var requestAnimFrame = (function () {
return wnd.requestAnimationFrame ||
wnd.webkitRequestAnimationFrame ||
wnd.mozRequestAnimationFrame ||
wnd.oRequestAnimationFrame ||
wnd.msRequestAnimationFrame ||
function (/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
答案 3 :(得分:0)
对我有用的唯一方法:
declare global {
interface Window {
requestAnimFrame(callback: () => void): any;
webkitRequestAnimationFrame(callback: () => void): any;
mozRequestAnimationFrame(callback: () => void): any;
oRequestAnimationFrame(callback: () => void): any;
}
}
Window.prototype.requestAnimFrame = function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
}