tmp dev
tmp dev

Reputation: 9193

Typescript create anonymous objects

I want to create a hierarchy of nested objects in typescript that looks like the following

snapshot{
   profile{
      data{
         firstName = 'a'
         lastName = 'aa'
      }
   }
} 

I dont want to create a class structure, just want to create the nested hierarchy of objects thats all.

Upvotes: 26

Views: 45290

Answers (2)

KrimblKrum
KrimblKrum

Reputation: 203

If you want TypeScript to enforce your anonymous object type, you can do the following. However, I recommend using this technique sparingly. If you have large complex objects, it will probably benefit you to call out an interface/class structure. Otherwise, the readability of your code may suffer.

let snapshot: {
  profile: {
    data: {
      firstName: string;
      lastName: string;
    };
  };
};

Upvotes: 1

Jon G Stødle
Jon G Stødle

Reputation: 3904

TypeScript is just JavaScript with some extra sugar on top, so regular anonymous JavaScript objects are legal:

var snapshot:any = {
   profile: {
      data: {
         firstName: 'a',
         lastName: 'aa'
      }
   }
}

Upvotes: 34

Related Questions