Understand interfaces

46 views Asked by At

I don't understand this code:

export interface MyType {
  [propertyName: string]: string | MyType;
}

I understand that types in a global way serve a function to generalize its use with the business objects of our applications. Types allow to capture the type the user provides in the function.

But in the above code I don't understand:

  • the usefulness of the syntax with brackets for the property;
  • the fact that the interface has a property whose value is the interface itself. Are interfaces recursive?
2

There are 2 answers

0
Puneet Sharma On

It is typescript not angular first

export interface MyType {
  [propertyName: string]: string | MyType;
}

And I think this is better use key

interface MyType {
  [key: string]: string | MyType;
}

in your example [] is used for key that can be string only. It can't be

let x : MyType = {1:"sss"}

Key should be string only like

let x : MyType = {"1":"sss"}

Answer The fact that the interface has a property whose value is the interface itself. Are the interfaces recursives

Yes they are

0
heaxyh On

The [propertyName:string] means this interface can have zero or multiple keys, like a map. Why the value could be again the same data type could be if you want to represent some child items or binary trees. Here is a example how this interface could be used:

interface MyType {
  [propertyName: string]: string | MyType;
}

const a : MyType = {foo: 'bar'}
const b : MyType = {key1: a, key2: 'bar', key3: 'three'}
const c : MyType = {a, b}

const bar: MyType = {
    a,
    b,
    c,
}

Playground