Skip to content

Convert Context/Provider/Subscription to Typescript #1742

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jun 26, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
7 changes: 6 additions & 1 deletion src/components/Context.js → src/components/Context.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import React from 'react'
import type Subscription from '../utils/Subscription'

export const ReactReduxContext = /*#__PURE__*/ React.createContext(null)
export type ReduxContextProps = {
store: any,
subscription: Subscription,
}
export const ReactReduxContext = /*#__PURE__*/ React.createContext<ReduxContextProps | null>(null)

if (process.env.NODE_ENV !== 'production') {
ReactReduxContext.displayName = 'ReactRedux'
Expand Down
8 changes: 4 additions & 4 deletions src/components/Provider.js → src/components/Provider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useMemo } from 'react'
import React, { ReactNode, useMemo } from 'react'
import PropTypes from 'prop-types'
import { ReactReduxContext } from './Context'
import { ReactReduxContext, ReduxContextProps } from './Context'
import Subscription from '../utils/Subscription'
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'

function Provider({ store, context, children }) {
function Provider({ store, context, children }: { store: any, context?: React.Context<ReduxContextProps>, children: ReactNode }) {
const contextValue = useMemo(() => {
const subscription = new Subscription(store)
subscription.onStateChange = subscription.notifyNestedSubs
Expand All @@ -25,7 +25,7 @@ function Provider({ store, context, children }) {
}
return () => {
subscription.tryUnsubscribe()
subscription.onStateChange = null
subscription.onStateChange = undefined
}
}, [contextValue, previousState])

Expand Down
43 changes: 27 additions & 16 deletions src/utils/Subscription.js → src/utils/Subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import { getBatch } from './batch'
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants

const nullListeners = { notify() {} }
type Listener = {
callback: () => void;
next: Listener | null;
prev: Listener | null;
};

function createListenerCollection() {
const batch = getBatch()
let first = null
let last = null
let first: Listener | null = null
let last: Listener | null = null

return {
clear() {
Expand Down Expand Up @@ -37,7 +41,7 @@ function createListenerCollection() {
return listeners
},

subscribe(callback) {
subscribe(callback: () => void) {
let isSubscribed = true

let listener = (last = {
Expand All @@ -57,6 +61,7 @@ function createListenerCollection() {
isSubscribed = false

if (listener.next) {
//@ts-expect-error -- listener.next is always null
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because listener is initialized on line 47 with next: null, Typescript interprets it as the following structure:

image

However when it gets to this line, it causes an error for potentially accessing this null field. It doesn't seem to realise that listener.next would prevent that from getting accessed.

image

I'm not entirely sure what's going on here -- either Typescript is wrong that listener.next is always null (though not sure how that would be), or Typescript is wrong that this null check isn't sufficient. Is there another option?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I sorted this by explicitly marking the variable as type Listener -- that ensured Typescript correctly interprets it as type Listener | null rather than null.

listener.next.prev = listener.prev
} else {
last = listener.prev
Expand All @@ -71,29 +76,35 @@ function createListenerCollection() {
}
}

type ListenerCollection = ReturnType<typeof createListenerCollection>;

export default class Subscription {
constructor(store, parentSub) {
private store: any;
private parentSub?: Subscription;
private unsubscribe?: () => void;
private listeners?: ListenerCollection;
public onStateChange?: () => void;

constructor(store: any, parentSub?: Subscription) {
this.store = store
this.parentSub = parentSub
this.unsubscribe = null
this.listeners = nullListeners
this.unsubscribe = undefined
this.listeners = undefined

this.handleChangeWrapper = this.handleChangeWrapper.bind(this)
}

addNestedSub(listener) {
addNestedSub(listener: () => void) {
this.trySubscribe()
return this.listeners.subscribe(listener)
return this.listeners?.subscribe(listener)
}

notifyNestedSubs() {
this.listeners.notify()
this.listeners?.notify()
}

handleChangeWrapper() {
if (this.onStateChange) {
this.onStateChange()
}
this.onStateChange?.()
}

isSubscribed() {
Expand All @@ -113,9 +124,9 @@ export default class Subscription {
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
this.unsubscribe = null
this.listeners.clear()
this.listeners = nullListeners
this.unsubscribe = undefined
this.listeners?.clear()
this.listeners = undefined;
}
}
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"emitDeclarationOnly": true,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
Expand Down