Typescript dynamic class methods -
problem
how can 1 add type checking dynamically created class method?
example
given simple property
class.
class property { value: any; name: string; constructor(name: string, value: any) { this.name = name; this.value = value } }
and entity
class
class entity { name: string; properties: property[]; constructor(name: string, properties: property[]) { this.name = name; this.properties = properties; this.properties.foreach((p: property, index: number) => { this[p.name] = (value: string): => { if (value) { this.properties[index].value = value; } return this.properties[index].value; } }, this); } }
important part: this[p.name] = function ...
(we don't know name of method @ "transpile" time).
we following error when transpiling javascript:
var car = new domain.entity( 'car', [ new domain.property('manufacturer', 'ford'), new domain.property('model', 'focus') ] ); car.model() // error ts2339: property 'model' not exist on type 'entity'.
i know uncommon use of classes different instances of entity
have different methods defined. there way rid of error, i.e. typescript able identify proper interface per instance, or @ least silent error?
notes
this valid javascript , 1 use in following manner:
var car = new domain.entity( 'car', [ new domain.property('manufacturer', 'ford'), new domain.property('model', 'focus') ] ); car.model() // 'focus' car.model('transit') // 'transit'
i'm aware has been asked on similar question, case different method name defined @ runtime.
if have dynamic properties want access use any type bypass type checks variable. can either declare variable any type go, or use type assertion operator (as) @ later point. here possible variants:
var car: = new domain.entity(...); car.model(); var car = new domain.entity(...) any; car.model(); var car = new domain.entity(...); (car any).model();
Comments
Post a Comment