does js/ts has something like impl in Rust or extension in Swift? this is a good pratice to implement method for object with a specific shape. and we can replace userSetAge(user, x => x + 1)
to user.setAge(x => x + 1)
. Not only that, it can still work after spread copyed object.
here is an example in React data fetching and render it:
interface User {
name: string;
age: number;
setAge(fn: (age: number) => number): User;
}
impl User {
setAge(self, fn) {
self.age = fn(self.age);
return this;
}
}
// it works
const eczn: User = { name: 'eczn', age: 17 };
({ ...eczn }).setAge(x => x + 1);
import useSWR, { mutate } from 'swr';
// React App
function UserCard(props: { user: User }) {
return (
<div onClick={() => {
mutate(
`/api/user/${props.user.name}`,
props.user.setAge(x => x + 1)
);
}}>
Current Age: { props.user.age }
</div>
)
}
function App() {
const { data, loading } = useSWR<User>('/api/user/eczn')
if (loading) return <div>loading ...</div>
return <UserCard user={{ ...data }} />
}
a bad implementation :: Object.prototype.setAge
Object.prototype.setAge = function(fn) {
this.age = fn(this.age);
}
const eczn: User = { name: 'eczn', age: 17 };
({ ...eczn }).setAge(x => x + 1);
obviously, it is a bad practice.