2016-05-18 45 views
6

Sto usando una libreria JS, in particolare select2 che agisce in modo leggermente diverso da quanto mi piacerebbe se gli oggetti che sto passando non fossero semplici oggetti. Questo è tutto controllato usando la funzione isPlainObject di jQuery.Come posso convertire un oggetto TypeScript in un oggetto semplice?

Does TypeScript ha un cast Non sono a conoscenza di ciò che otterrebbe questo senza ricorrere a scrivere il mio?

class Opt { 
    constructor(public id, public text) { 

    } 

    toPlainObj(): Object { 
     return { 
      id: this.id, 
      text: this.text 
     } 
    } 
} 

let opts = [ 
    new Opt(0, 'foo'), 
    new Opt(1, 'bar') 
]; 

console.clear() 

console.log('both should be false') 
$.map(opts, opt => { 
    console.log($.isPlainObject(opt)) 
}) 

console.log('both should be true') 
$.map(opts, opt => { 
    console.log($.isPlainObject(opt.toPlainObj())) 
}) 
+0

si prega di inviare il vostro codice qui – messerbill

+0

@messerbill Non credo che Snippet di codice SO supportino TypeScript. Almeno, non riesco a farlo funzionare. –

+0

basta digitarlo qui - non è necessario utilizzare la funzionalità snippet di codice – messerbill

risposta

8

È possibile utilizzare Object.assign():

class Point { 
    private x: number; 
    private y: number; 

    constructor(x: number, y: number) { 
     this.x = x; 
     this.y = y; 
    } 

    getX(): number { 
     return this.x; 
    } 

    getY(): number { 
     return this.y; 
    } 
} 

let p1 = new Point(4, 5); 
let p2 = Object.assign({}, p1); 

p1 è l'istanza di classe, e p2 è solo { x: 4, y: 5 }.

E con il metodo toPlainObj:

class Point { 
    private x: number; 
    private y: number; 

    constructor(x: number, y: number) { 
     this.x = x; 
     this.y = y; 
    } 

    getX(): number { 
     return this.x; 
    } 

    getY(): number { 
     return this.y; 
    } 

    toPlainObj(): { x: number, y: number } { 
     return Object.assign({}, this); 
    } 
} 

Se questo è qualcosa che dovete in più classi, allora si può avere una classe di base che ha questo metodo:

class BaseClass<T> { 
    toPlainObj(): T { 
     return Object.assign({}, this); 
    } 
} 

class Point extends BaseClass<{ x: number, y: number }> { 
    private x: number; 
    private y: number; 

    constructor(x: number, y: number) { 
     super(); 

     this.x = x; 
     this.y = y; 
    } 

    getX(): number { 
     return this.x; 
    } 

    getY(): number { 
     return this.y; 
    } 
} 
Problemi correlati