electricessence / TypeScript.NET

A JavaScript-Friendly .NET Based TypeScript Library (Moved)
https://github.com/electricessence/TypeScript.NET-Core
Other
251 stars 36 forks source link

using (IDisposable) in functions not returning void #50

Closed WalterLeinert closed 8 years ago

WalterLeinert commented 8 years ago

Hi,

tried to port some logging helper from c#/java to typescript. The class EnterExitLogger is disposable and logs function entry (constructor) and exit (dispose).

The following usage works as expected: protected usingTester() { var logger; using(logger = new EnterExitLogger(log, Log.Level.DEBUG, 'usingTester'), () => { return 1234; }); }

But when I have a function returning a value, I get a typescript error: protected usingTesterReturn(): number { var logger; using(logger = new EnterExitLogger(log, Log.Level.DEBUG, 'usingTesterReturn'), () => { return 1234; }); }

Error: A function whose declared type is neither 'void' nor 'any' must return a value.

Do you have any idea how to handle this issue?

Regards, Walter

electricessence commented 8 years ago

Might be a couple of things... Might I suggest these changes:

protected usingTesterReturn(): number {
    return using(  // Note: I'm returning whatever the using returns. **
        new EnterExitLogger(log, Log.Level.DEBUG, 'usingTesterReturn'),
        logger => {
            // ... Do some logger stuff.
            return 1234; // Needs to match the return type of the function. **
        }
    );
}

Lemme know if you're having trouble understanding the using keyword usage here. https://github.com/electricessence/TypeScript.NET/blob/master/source/System/Disposable/dispose.ts#L75-L102

WalterLeinert commented 8 years ago

Thank you so much, you suggestion works. I wrote many implementations of the disposable pattern in c#/.net; but in c# the compiler generates the corresponding code, so returning nothing or something from a disposable scope was no issue.

As I understand this is not possible with this kind of implementation in typescript/javascript.

Regards, Walter

electricessence commented 8 years ago

@WalterLeinert You are correct. A true disposable is not something you can expect from a JS environment. Because the GC doesn't really have a means to signal if the object is ready. But the pattern is still useful because you can propagate explicit cleanup routines.

The 'using' keyword in this case seems to work well as a means of simplifying your code and not producing externalized scope. The 'return' value is simply a convience that would not be provided by C# because in this case we are wrapping our code in a function. As I understand it, it's much better to return the value from the function versus relying on scoping and closures.

electricessence commented 8 years ago

@WalterLeinert. What is your experience with TypeScript so far? How are you liking the library? Check out my YouTube for more TypeScript tips: https://www.youtube.com/channel/UCG2QyAgVUEKSMBaC0Fkp5GQ