const passedObject = {
firstName: "Saoirse",
lastName: "Ronan",
age: 26,
};
function makeWatchedObject<T>(object: T) {
return {
...object,
on<Key extends string & keyof T>(eventName: `${Key}Changed`, callback: (newValue: T[Key]) => any) {
}
};
}
const obj = makeWatchedObject(passedObject);
// how does it work that the newValue is typed correctly even though I pass 'firstNameChanged' not 'firstName'?
obj.on('firstNameChanged', newValue => newValue + 1);
// I thought this call equals to ->
// obj.on<'firstNameChanged'>('firstNameChanged', newValue => newValue + 1)
// but it seems that inside this generic function it captures only 'firstName...' part, not the whole string 'firstNameChanged'
#Why does this generic function work?
7 messages · Page 1 of 1 (latest)
Preview:```ts
const passedObject = {
firstName: "Saoirse",
lastName: "Ronan",
age: 26,
};
function makeWatchedObject<T>(object: T) {
return {
...object,
on<Key extends string & keyof T>(eventName: ${Key}Changed, callback: (newValue: T[Key]) => any) {
}
};
}
const obj = makeWatchedObject(passedObject);
// how does it work that the newValue is typed correctly even though I pass 'firstNameChanged' not 'firstName'?
obj.on('firstNameChanged', newValue => newValue + 1);
// I thought this call equals to ->
...```
is this your code or someone else's? maybe you missed the eventName: `${Key}Changed` part?
Key is inferred as the part of the string before 'Changed'
why in this case Key='firstName' and not Key='firstNameChanged' ?
I thought Key=Argument you passed='firstNameChanged' not just 'firstName'