#Why does this generic function work?

7 messages · Page 1 of 1 (latest)

frosty patrol
#
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'
sleek nightBOT
#
.iwasframed#0

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 ->
...```

topaz thicket
#

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'

frosty patrol
topaz thicket
#

the argument you pass is typed as eventName: `${Key}Changed` , not eventName: Key

#

so Key is inferred as the part before 'Changed'