I'm using Backbone.Marionette in Typescript. I've written my own type description of Marionette.
var ProviderSpa = new Backbone.Marionette.Application();
ProviderSpa.addRegions({
'servicesRegion': "#services-offered"
});
ProviderSpa.servicesRegion.show();
My problem is that addRegions has a side effect of adding properties to ProviderSpa, which TypeScript doesn't know about and therefore it complains that 'The property 'servicesRegion' does not exist on value of type 'Backbone.Marionette.Application'.
How can I tell TypeScript about these dynamic property additions to an instance of a type?
Dynamically add Properties to an Object in TypeScript Borislav Hadzhiev Thu Feb 24 2022·3 minread Photo byRobson Morgan Dynamically add Properties to an Object in TypeScript# Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {}.
The type of myVar is a string, and not all strings are properties of the object, so TypeScript informs us that we can't safely access the property dynamically. If you try to set the type of myVar to be a union of the object's keys, you would still get an error. The easiest way to get around this is to use a type assertion.
Use an index signature to dynamically add properties to an object, e.g. `const obj: {[key: string]: any} = {}`. Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time. HomeAboutContacts HomeAboutContacts GitHubLinkedinTwitter
No, you cannot dynamically change an interface as it is a static value, used for static, structural type checking by the Typescript compiler. However, you ca... Exploring options for adding properties to Typescript interfaces. Vince Campanale/Blog/ AboutBlogPortfolio Can I dynamically add properties to an interface in Typescript? Jan 12, 2018
I have used a cut down definition of BackBone Marionette for this example.
If you have lots of dynamic properties being added to an object, you might want to leave things dynamic rather than attempting to create declarations or interfaces for them all - especially as the overhead of keeping declarations up-to-date with new properties vs the benefits of having static typing on what are actually dynamic properties isn't a cost I would pay.
In this example, accessing the property using square-bracket syntax means it passes the type checking without the need for a declaration. The important bit is on the last line.
You can test this on the TypeScript playground.
declare module Backbone {
export module Marionette {
export class Application {
addRegions(regions: any): void;
}
}
}
var servicesRegion = 'servicesRegion';
var ProviderSpa = new Backbone.Marionette.Application();
ProviderSpa.addRegions({
servicesRegion: "#services-offered"
});
ProviderSpa[servicesRegion].show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With