Skip to content

Commit 847ae94

Browse files
committed
Add TypeScript declarations for requestIdleCallback and cancelIdleCallback
requestIdleCallback and cancelIdleCallback exist at runtime on both architectures and are declared in the Flow libdefs, but the public TypeScript types never included them. React Native projects compile without lib: ["dom"], so the API was invisible to TypeScript users - Added the declarations to src/types/globals.d.ts - Add type tests in __typetests__/globals.tsx
1 parent cb0cf07 commit 847ae94

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

packages/react-native/__typetests__/globals.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,25 @@ function testRequestAnimationFrame(){
137137
);
138138
}
139139

140+
function testRequestIdleCallback() {
141+
let handle = requestIdleCallback(deadline => {
142+
const didTimeout: boolean = deadline.didTimeout;
143+
const remaining: number = deadline.timeRemaining();
144+
console.log(didTimeout, remaining);
145+
});
146+
cancelIdleCallback(handle);
147+
148+
handle = requestIdleCallback(noop, { timeout: 100 });
149+
cancelIdleCallback(handle);
150+
151+
// @ts-expect-error
152+
requestIdleCallback(noop, { timeout: 'wrong-type' });
153+
154+
// handle is opaque: object on New Architecture, number on legacy
155+
// @ts-expect-error
156+
const handleIsNotNumber: number = requestIdleCallback(noop);
157+
}
158+
140159
const fetchCopy: WindowOrWorkerGlobalScope['fetch'] = fetch;
141160

142161
const myHeaders = new Headers();

packages/react-native/src/types/globals.d.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,16 @@ declare global {
125125
function cancelAnimationFrame(handle: number | null | undefined): void;
126126
function requestAnimationFrame(callback: (time: number) => void): number;
127127

128+
type IdleCallbackID = unknown;
129+
function requestIdleCallback(
130+
callback: (deadline: {
131+
didTimeout: boolean;
132+
timeRemaining: () => number;
133+
}) => void,
134+
options?: {timeout: number},
135+
): IdleCallbackID;
136+
function cancelIdleCallback(handle: IdleCallbackID): void;
137+
128138
function fetchBundle(
129139
bundleId: number,
130140
callback: (error?: Error | null) => void,

0 commit comments

Comments
 (0)