سؤال

I'm using TypeScript with Angular. I'm interested in adding to the scope of a controller a pair of functions, currentPath(): string and currentPath(newValue: string): void, and forbid direct access to the backing variable. I also wanted to factor out this “property-like” behaviour. So I added an interface:

interface Property<T> {
    (): T;
    (newValue: T): void;
}

And then tried to configure my scope like this:

interface ApplicationRootScope extends ng.IScope {
    currentPath: Property<string>;
}

appControllers.controller('MyCtrl', ($scope: ApplicationRootScope) => {
    var _currentPath = "n/a";
    $scope.currentPath = { // this assignment fails
        (): string = _currentPath;
        (newValue: string) => {
            _currentPath = newValue;
        }
    };
});

The assignment at the marked line fails — I'm using wrong syntax on purpose to demonstrate what I'd like to do. Is there any way for me to assign the currentPath variable directly like this?

هل كانت مفيدة؟

المحلول

Function overloading is only a type system feature; JavaScript/TypeScript does not directly support overloading on function arity.

What you want to write is this:

$scope.currentPath = function(arg?: string) {
    if(arguments.length === 0) {
        return _currentPath;
    } else {
        return _currentPath = arg;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top