Response to «TypeScript React Beauty in the Eye of the Handler»
Here's my answer to Caleb's posted question TypeScript React Beauty in the Eye of the Handler 1:
First, I'd try to leverage composition as much as possible. Let's define a function named compose that accepts any number of arguments, expecting them to all be 1-artity functions. This will return a 1-arity function that will pipe the given argument through each function in turn.
const compose = (...fns) => (initialVal) => fns.reduce((val, fn) => fn(val), initialVal)
Next, I'd pull any commonly used logic that I'd like to compose into some kind of helper function.
const selectValue = (event) => (event.currentTarget.value)
const parseBaseTen = (number) => (parseInt(number, 10))
With just those two steps, the composition can be made simple! Personally, I'd put the composition inline with the other values. I don't see much value from extracting it into another named constant.
const HeightWidthComponent = () => {
const [width, setWidth] = useState(512)
const [height, setHeight] = useState(332)
return (
<div>
<input type='number' name='width' min={320} defaultValue={512} onChange={compose(selectValue, parseBaseTen, setWidth)} step={1} />
<input type="number" name="height" min={258} defaultValue={332} onChange={compose(selectValue, parseBaseTen, setHeight)} step={1} />
</div>
)
}
However, I didn't have a quick and easy way to verify that Typescript is able to type-check this variation. Let me know whether it's able to or not!
Note the
rel="snub:reply"in the anchor indicating that this article is a reply to the linked article. See my article on SNUB for conceptual details.↩