2016-07-05 51 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但它的被裝飾者添加。