Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript create anonymous objects

Tags:

typescript

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.

like image 452
tmp dev Avatar asked Jul 20 '17 06:07

tmp dev


People also ask

How do I create an anonymous class in TypeScript?

Create anonymous class extends superclass via class extends ? test('anonymous class extends superclass by `class extends ?`', () => { let stub = jest. fn(); let AntTask: {new(name: string): Task} = class extends Task { //anonymous class auto inherit its superclass constructor if you don't declare a constructor here.

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

Can an object be anonymous?

An anonymous object is basically a value that has been created but has no name. Since they have no name, there's no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.

How do I create a new object in TypeScript?

Creating standalone objects in typescript: As Fundamentally, Javascript runs with Template-based code snippets, we can create objects directly without creating classes, with taking help of Object Literals and constructor method.


2 Answers

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'
      }
   }
}
like image 120
Jon G Stødle Avatar answered Oct 23 '22 20:10

Jon G Stødle


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;
    };
  };
};
like image 1
KrimblKrum Avatar answered Oct 23 '22 22:10

KrimblKrum