2016-07-05 63 views
1

是否有通过装饰添加功能的有效方法?通过装饰添加功能

装饰:

function testDecorator(options){ 
    return function(target){ 
     target.test = function() { 
      console.log('Zipp Zapp!'); 
     }; 
    } 
} 

类别:

@testDecorator({}) 
class Book{ 

} 

使用(在这种情况下优选的),如在

Book.test() 

打字稿编译结果:

Property 'test' does not exist on type 'typeof Book'.

使用像

var b = new Book(); 
b.test(); 

打字稿编译结果:

Property 'test' does not exist on type 'Book'

回答

1

那是因为你的Book类/实例不具有此功能test的定义。

可以为Book.test版本做到这一点:

function testDecorator(options) { 
    return function(target) { 
     target.test = function() { 
      console.log('Zipp Zapp!'); 
     }; 
    } 
} 

interface BookConstructor { 
    new(): Book; 
    test(): void; 
} 

@testDecorator({}) 
class Book {} 

(Book as BookConstructor).test(); 

code in playground

或者这对于new Book().test版本:

function testDecorator(options) { 
    return function(target) { 
     target.prototype.test = function() { 
      console.log('Zipp Zapp!'); 
     }; 
    } 
} 

interface Testable { 
    test(): void; 
} 

@testDecorator({}) 
class Book {} 

let b = new Book(); 
(b as Testable).test(); 

code in playground

主要这里的区别是t帽子,我们正在做的:

target.prototype.test = function() { ... } 

相反的:

target.test = function() { ... } 

在这两种情况下,你需要转换,因为Book对象/类不声明实例/静态方法test但它的被装饰者添加。