How can i get the name of the sub class (which is invoking the constructor of base class) from base class itself in TypeScript
. I have code setup as:
class Animal{
constructor(){ console.log(this.constructor.name)} //this is throwing error}
}
class Cow extends Animal{
constructor(){ super() }
}
new Cow() // this should log "Cow"
In plane Js
this.constructor.name
used to work but seems like this is not the case in TypeScript
. The error I'm getting is :
error TS2339: Property 'name' does not exist on type 'Function'.
Please help. Thank you
The only reason this should fail is in Internet Explorer / IE Mobile, as the Function.name
basic support is not present. In all other browsers, it should work.
This even works if you target ESNEXT
and the output contains ECMAScript classes (ie like the TypeScript does). The below code will work in your fast-paced happy browsers... and if you run it through the TypeScript compiler, the plain version works too (except as stated above).
class Animal { constructor() { console.log(this.constructor.name); } } class Cow extends Animal{ constructor() { super(); } } new Cow();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.