Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Methods in TypeScript

In pure JavaScript we can do it:

var x = {
    y: {
        a: function() {},
        b: function(o, e) {}
    },
    z: function() {}
}

By using the syntactic sugar of class in TypeScript can we nest methods? Something like the pseudo-code:

class x {
    y: {
        a() {};
        b() {};
    }
    z() {};
}

And thus call:

> x.y.a
< function() {}
> x.y.b
< function() {}
> x.y
< [Object object]
> x.z
> function() {}

Using namespace-like, but not entering inside modules and others. Just by classes. When I do in pure JS, it works, but how to port the first code to TypeScript?

like image 665
Marcelo Camargo Avatar asked Sep 15 '25 11:09

Marcelo Camargo


2 Answers

Here you go :

class X {
    y = {
        a:()=> {},
        b:()=> {}
    }
    z() {}
}

var x = new X();
like image 109
basarat Avatar answered Sep 16 '25 23:09

basarat


The .y property can be typed as a separate class:

class Y {
    a() {}
    b(o, e) {}
}
class X {
    y = new Y();
    z() {}
}

By the way, these are not "nested methods". Nested methods would be functions inside functions, more like this:

function outer() {
    function nested() {
        // code...
    }
}
like image 26
Douglas Avatar answered Sep 17 '25 00:09

Douglas