Consider the following code:
const subscriptions: { [key: string]: [() => void] } = {}
interface ISubscription {
eventName: string
callback: () => void
}
export function unsubscribe({ eventName, callback }: ISubscription) {
if (!subscriptions[eventName]) { return }
const index = subscriptions[eventName].findIndex((l) => l === callback)
if (index < 0) { return }
subscriptions[eventName].splice(index, 1)
}
export function subscribe({ eventName, callback }: ISubscription) {
if (!subscriptions[eventName]) {
subscriptions[eventName] = []
}
subscriptions[eventName].push(callback)
return () => unsubscribe({ eventName, callback })
}
The issue typescript reports is:
TS2741: Property '0' is missing in type '[]' but required in type '[() => void]'.
Which comes from trying to assign an empty array to the subscriptions:
if (!subscriptions[eventName]) {
subscriptions[eventName] = []
}
This can be fixed by defining the interface to accept an empty array but then there's an issue when assigning a callback:
const subscriptions: { [key: string]: [() => void] | [] } = {}
TS2345: Argument of type '() => void' is not assignable to parameter of type 'never'.
A workaround would be:
const subscriptions: { [key: string]: [() => void] } = {}
if (!subscriptions[eventName]) {
subscriptions[eventName] = [callback]
}
else {
subscriptions[eventName].push(callback)
}
What is the correct way to be able to set it to an empty array and then assign the callback? I tried using the question mark too but I can't seem to get it right. Thank you for your help.