Skip to content

Commit

Permalink
improve infering the return type
Browse files Browse the repository at this point in the history
  • Loading branch information
nikgraf committed Jun 26, 2024
1 parent 8046f4c commit f3947fa
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion examples/app/src/components/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const Settings: React.FC = () => {
// initialize a Y.Doc and get the settings
// when the component mounts
const yDoc = new Y.Doc();
const ySettings = yDoc.getMap("settings");
const ySettings = yDoc.getMap<boolean>("settings");
ySettings.set("weeklyReminderEmail", true);
return ySettings;
});
Expand Down
4 changes: 2 additions & 2 deletions examples/app/src/components/Todos.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const Todos: React.FC = () => {
<label>
<input
type="checkbox"
checked={todo.checked}
checked={todo.checked as boolean}
onChange={(event) => {
yTodos
.get(index)
Expand All @@ -52,7 +52,7 @@ export const Todos: React.FC = () => {
/>
<input
type="text"
value={todo.text}
value={todo.text as string}
onChange={(event) => {
yTodos.get(index).set("text", event.currentTarget.value);
}}
Expand Down
19 changes: 12 additions & 7 deletions packages/react-yjs/src/useY.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ import { useRef, useSyncExternalStore } from "react";
import * as Y from "yjs";
import { YJsonValue } from "./types.js";

type YTypeToJson<YType> =
YType extends Y.Array<infer Value>
? Array<YTypeToJson<Value>>
: YType extends Y.Map<infer MapValue>
? { [key: string]: YTypeToJson<MapValue> }
: YType extends Y.XmlFragment | Y.XmlText | Y.XmlElement
? string
: YType;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useY(yData: Y.Array<any>): any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useY(yData: Y.Map<any>): Record<string, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useY(yData: Y.XmlElement | Y.XmlFragment | Y.Text): string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useY(yData: any): any {
export function useY<YType extends Y.AbstractType<any>>(
yData: YType
): YTypeToJson<YType> {
const prevDataRef = useRef<YJsonValue | null>(null);
return useSyncExternalStore(
(callback) => {
Expand Down

0 comments on commit f3947fa

Please sign in to comment.