#How to type 'this' in wrapped function in a object that's being initialized?

6 messages · Page 1 of 1 (latest)

rustic cave
#
function getAPI() {
    return {
        display_hello() {
            console.log('hello')
        },

        display_world: lodash_throttle(() => {
            // how to use display_hello in this situation?
            this.display_hello(); // error: 'this' implicitly has type 'any' because it does not have a type annotation.
        }, 1000)
    };
}

function lodash_throttle(f: () => void, ms: number) {
    // just an example, doesn't throttle anything
    return f;
}

Link to playground: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQIIAUCSAKASkQG8AoRCxAJ3RCqTMqcQBMYBnABwBsBDATwD6AC1TducQiXLNZEBOzjdUAOgnI8AclHi4mgjNkBfADSlDzNlz5CA7nCrcWALkQSWvdsMFRhVOFBQynhSALwAfNKysgD0MYjCcLaIUHCIIOyorBw8AiJiEogwSL4ciOwwUCC8sAgA-BbRKcIcKla5QjoShADciHGIqFT+VK6apeyaRQC2PDAQldz8CZ4p-JxZmrxg-FMARqgQvBlZlaxwqOyIYAErAG5ZvGsbiNs3UDXwYCqNlKaIAEYAAwggxMIw9UhGcygSC1JDuTzeXz+QLBYCuMKRO5wGAsEyIabsVxgEDTA5UIiMSgDABWGSgryQqAAHrxZsoCSwLuwwONmqigo8dqUwMgLDQqvREMBIUYgA

formal obsidian
#

because of how you've written display_world (as a property that is bound to the return value off another function), this will be undefined there at runtime (i.e. this isn't just a type error, it's a runtime error)

#

if you use method syntax instead this will be bound automatically, and typescript understands that:

#
#

hmm, the bot must be asleep