Add property to interface typescript Add property to interface typescript typescript typescript

Add property to interface typescript


You cannot dynamically change / create an interface as it is just a static value, used for structural type checking by the Typescript compiler.

However, if you need all the properties on that interface and an additional property, you can do a few things:

Use extends

You can also use extends to create a new interface for this specific case.

interface ExtendedUserData extends UserData { someOtherProperty: string}

Use Intersection types

This may be close to the sort of "dynamic" behavior you're looking for. Say you have a property that needs to be an object with all the properties of UserData and an additional extraProperty.

You can type it like this.

fancyUserData: UserData & { extraProperty: string }

With intersection types you can add properties ad hoc.

Usage in Angular

In order to use these types in angular, you can create a generic type on your component that would look something like this:

@Component({  selector: 'example'  template: `<h1>example</h1>`})export class ExampleComponent<T extends UserData> {}

Now you can have data of type T which must have all of the UserData properties, then add whatever other properties you'd like.

So in short, no you can't really build dynamic types, and definitely not in the component's constructor. However, you can use the methods I mentioned above to extend and mold your interfaces on an as needed basis.