简体   繁体   中英

Add property to interface typescript

So I'm working on an Angular Project and created this interface to be able to show some data:

export interface UserData {
  name: string,
  vorname: string,
  strasse: string,
  plz: string,
  ort: string,
  handynummer: string,
  telefonnummer: string,
}

If I want to show add more Data in my database, i would have to add these datapoint to this interface, is there a way to create a interface dynamically, or create it in the Components Constructor?

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.

To add a property you can define the same interface again and add the additional properties:

interface SquareConfig {
  color?: string;
  width?: number;
}

interface SquareConfig {
  name: string;
}

let c: SquareConfig = {name:'jack', color:'blue'}
console.log(c) // {"name": "jack", "color": "blue"} 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM