Skip to content

Instantly share code, notes, and snippets.

@michelsalib
Created April 23, 2015 13:17
Show Gist options
  • Save michelsalib/cfff8114ce081930a453 to your computer and use it in GitHub Desktop.
Save michelsalib/cfff8114ce081930a453 to your computer and use it in GitHub Desktop.
Typescript @deprecated annotation
class Dog {
@deprecated('Dogs don\'t roar, they talk.')
roar() {
console.log('RRRRR');
}
@deprecated()
smile() {
console.log('smile');
}
walk() {
console.log('walk');
}
}
function deprecated(message: string = 'Function {name} is deprecated.') {
return (instance, name, descriptor) => {
var original = descriptor.value;
var localMessage = message.replace('{name}', name);
descriptor.value = function() {
console.warn(localMessage);
return original.apply(instance, arguments);
};
return descriptor;
};
}
// create my dog
var d = new Dog();
d.roar();
d.smile();
d.walk();
@psulek
Copy link

psulek commented May 15, 2017

This look good, but it does not work with Promise.

@gatsbyz
Copy link

gatsbyz commented Oct 19, 2018

Does not work with Promise.

@Jeff-Tian
Copy link

This works great with functions, but it does not work with classes.

@Jeff-Tian
Copy link

Another issue, the line 25 uses instance which will cause this issue. Change it to this will be OK:

export default function deprecated(message: string = 'Function {name} is deprecated.') {
  return (instance: any, name: string, descriptor: any) => {
    console.log('ins for ', name, ' = ', instance);
    let original = descriptor.value;
    let localMessage = message.replace('{name}', name);

    descriptor.value = function() {
      console.warn(localMessage);

      // Use `this` instead of `instance`:
      return original.apply(this, arguments);
    };

    return descriptor;
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment