Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/hooks/src/__tests__/refTypes.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import { describe, expect, test } from 'vitest';

const emitDeclaration = (sourceFile: string) => {
let declaration = '';
const program = ts.createProgram([sourceFile], {
declaration: true,
emitDeclarationOnly: true,
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
skipLibCheck: true,
strictNullChecks: true,
target: ts.ScriptTarget.ES2015,
types: [],
});

const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length > 0) {
throw new Error(
ts.formatDiagnosticsWithColorAndContext(diagnostics, {
getCanonicalFileName: (fileName) => fileName,
getCurrentDirectory: () => process.cwd(),
getNewLine: () => '\n',
}),
);
}

const emitResult = program.emit(undefined, (fileName, text) => {
if (fileName.endsWith('.d.ts')) {
declaration = text;
}
});

expect(emitResult.emitSkipped).toBe(false);
return declaration;
};

describe('ref return type declarations', () => {
test.each([
[
'useLatest',
'../useLatest/index.ts',
'declare function useLatest<T>(value: T): MutableRefObject<T>;',
],
[
'useUnmountedRef',
'../useUnmountedRef/index.tsx',
'declare const useUnmountedRef: () => MutableRefObject<boolean>;',
],
])('%s should expose a non-nullable mutable ref', (_hook, sourcePath, expected) => {
const sourceFile = fileURLToPath(new URL(sourcePath, import.meta.url));
expect(emitDeclaration(sourceFile)).toContain(expected);
});
});
3 changes: 2 additions & 1 deletion packages/hooks/src/useLatest/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MutableRefObject } from 'react';
import { useRef } from 'react';

function useLatest<T>(value: T) {
function useLatest<T>(value: T): MutableRefObject<T> {
const ref = useRef(value);
ref.current = value;

Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useUnmountedRef/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MutableRefObject } from 'react';
import { useEffect, useRef } from 'react';

const useUnmountedRef = () => {
const useUnmountedRef = (): MutableRefObject<boolean> => {
const unmountedRef = useRef(false);
useEffect(() => {
unmountedRef.current = false;
Expand Down
Loading