26

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.

2 Answers 2

34

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'
      }
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but how do I specify a type of firstName?
1

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;
    };
  };
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.