To get this value, use the wp.data objectmodule.
const template = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'template' );
Since this can be changed in the document settings, you would likely need to "subscribe" and run a callback whenever this changes.
For example:
const { select, subscribe } = wp.data;
class PageTemplateSwitcher {
constructor() {
this.template = null;
}
init() {
subscribe( () => {
const newTemplate = select( 'core/editor' ).getEditedPostAttribute( 'template' );
if ( newTemplate && newTemplate !== this.template ) {
this.template = newTemplate;
this.changeTemplate();
}
});
}
changeTemplate() {
// do your stuff here
console.log(`template changed to ${this.template}`);
}
}
new PageTemplateSwitcher().init();