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.
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.
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 .
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.
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.
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'
}
}
}
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;
};
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With