Issue
I want to create a Typescript class RepeatLoader whose job is to take a function, which loads some data and will be run in a while loop until a callback which checks whether some condition is true stops it.
This currently looks something like this:
class RepeatLoader() {
loadDataFunc: () => void,
shouldLoadCallback: () => boolean
constructor(loadDataFunc, shouldLoadCallback) {
this.loadDataFunc = loadDataFunc;
this.shouldLoadCallback = shouldLoadCallback
}
startRunning() {
while(this.shouldLoadCallback()) {
this.loadDataFunc()
sleep(3000)
}
}
}
I would like to be able to pass dynamic parameters to the loadDataFunc. Something like a loadDataParams object that either gets passed through the constructor or the startRunning function.
Coming from Python, this would be a textbook example for **kwargs. But I'm not sure how to do this in Typescript. Does someone have suggestions?
Thanks in advance.
Solution
You could use generics:
class RepeatLoader<A extends unknown[]> {
loadDataFunc: (...args: A) => void
shouldLoadCallback: () => boolean
constructor(loadDataFunc: (...args: A) => void, shouldLoadCallback: () => boolean) {
this.loadDataFunc = loadDataFunc
this.shouldLoadCallback = shouldLoadCallback
}
startRunning(...args: A) {
while (this.shouldLoadCallback()) {
this.loadDataFunc(...args)
sleep(3000)
}
}
}
// Usage:
const shouldLoadCallback = (): boolean => { /* ... */ }
const foo = new RepeatLoader(
(x: number, y: number) => console.log(x + y),
shouldLoadCallback
)
foo.startRunning(1, 2)
const bar = new RepeatLoader(
({x, y}: {x: number; y: number}) => console.log(x + y),
shouldLoadCallback
)
bar.startRunning({x: 1, y: 2})
- The
A extends unknown[]
means thatA
needs to be some kind of array, which allows us to do(...args: A)
- The
(...args: A)
is like Python’s*args
- The closest thing you can get to Python’s
**kwargs
is by doing something likebar
in the example above: using a single object parameter
If you only want loadDataFunc
to take one parameter, you can do this:
class RepeatLoader<T> {
loadDataFunc: (arg: T) => void
shouldLoadCallback: () => boolean
constructor(loadDataFunc: (arg: T) => void, shouldLoadCallback: () => boolean) {
this.loadDataFunc = loadDataFunc
this.shouldLoadCallback = shouldLoadCallback
}
startRunning(arg: T) {
while (this.shouldLoadCallback()) {
this.loadDataFunc(arg)
sleep(3000)
}
}
}
but the first way is more general.
Answered By - cherryblossom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.