2016-07-26 17 views
5

uczę kątową 2 i Pisałem definicję ts dla metody obcinania chcę użyć w jednym z moich usług.jak to prototyp w maszynopisie

truncate.ts

interface String { 
    truncate(max: number, decorator: string): string; 
} 

String.prototype.truncate = function(max, decorator){ 
    decorator = decorator || '...'; 
    return (this.length > max ? this.substring(0,max)+decorator : this); 
}; 

Jak importować to pod innym modułem maszynopis lub przynajmniej udostępnić go używać na całym świecie.

Odpowiedz

3

użyciu maszynopis 2.3.4 w Ionic 3 4 kątowa aplikacji utworzyć plik o nazwie stringExtensions.ts i umieścić to w nim

export { } // to make it a module 

declare global { // to access the global type String 
    interface String { 
     truncate(max: number, decorator: string): string; 
    } 
} 

// then the actual code 
String.prototype.truncate = function(max, decorator){ 
    decorator = decorator || '...'; 
    return (this.length > max ? this.substring(0,max)+decorator : this); 
}; 
+0

dlaczego downwise? – Peter

+1

przy użyciu export {} & declare global {} był magicznym sosem dla mnie w porównaniu z innymi przykładami ... a następnie dla zapisu, nie musiałem robić żadnego innego importu w moim zakresie użycia według innych przykładów. Dzięki Peter! – Beej

9

Jak mogę to zaimportować do innego modułu skryptu maszynowego lub przynajmniej udostępnić go do wykorzystania na całym świecie.

przenieść go do pliku stringExtenions.ts:

interface String { 
    truncate(max: number, decorator: string): string; 
} 


String.prototype.truncate = function(max, decorator){ 
    decorator = decorator || '...'; 
    return (this.length > max ? this.substring(0,max)+decorator : this); 
}; 

i zaimportować plik jak:

import "./stringExtensions" 

Więcej

https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

+0

to kompiluje ale metoda skracania nie wydaje się działać – Peter