0

I know that all javascript is valid typescript but I'd like to start converting my javascript to typescript conventions. I'm battling this one snippet of JS:

My standard Javascript that works

if (MyCompany === undefined) {
    var MyCompany = {};
}
MyCompany.Uploader = MyCompany.Uploader || {};
MyCompany.Uploader.Core = function (config) {
    'use strict';
    function build() {
        console.log("building");
    }
    return {
        build: build
    };
};
var config = {this: "that};
MyCompany.Uploader.Core(config).build(); // outputs building to console

I've been messing with multiple approaches and I feel like I not close enough.

My failed attempt at converting to Typescript

namespace MyCompany.Uploader {
    export var Core = (config:any) => {
        function build() {
            console.log("building");
        }
    };
}
let configobj = {here:"there"};
MyCompany.Uploader.Core(configobj).build();

This simply doesn't work. I can't seem to access the build function. I'm sure this is a rookie mistake.

The error I get: Property build does not exist on type void

1 Answer 1

0

That's because you did not add an important part of your javascript code into the typescript version, and that's the return object which contains the reference for the build function, it should be:

namespace MyCompany.Uploader {
    export var Core = (config: any) {
        function build() {
            console.log("building");
        }

        return {
            build: build
        }
    };
}

let configobj = { here: "there" };
MyCompany.Uploader.Core(configobj).build();

You can also define interfaces for the config and the return object:

namespace MyCompany.Uploader {
    export interface Config {
        here: string;
    }

    export interface Builder {
        build: () => void;
    }

    export var Core = (config: Config): Builder => {
        function build() {
            console.log(config.here);
        }

        return {
            build: build
        }
    };
}

let configobj = { here: "there" };
MyCompany.Uploader.Core(configobj).build();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I think i got so caught up in how Typescript is different that I forgot principles that are the same between each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.