简体   繁体   English

将命名空间的Javascript函数转换为Typescript

[英]Convert Namespaced Javascript Functions to Typescript

I know that all javascript is valid typescript but I'd like to start converting my javascript to typescript conventions. 我知道所有javascript都是有效的打字稿,但我想开始将我的javascript转换为打字稿约定。 I'm battling this one snippet of JS: 我正在与JS的这一小片段作斗争:

My standard Javascript that works 我的标准Javascript有效

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 我尝试转换为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 我收到的错误: void类型上不存在属性构建

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: 这是因为您没有将JavaScript代码的重要部分添加到打字稿版本中,而这是包含build函数引用的返回对象,它应该是:

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: 您还可以为config和return对象定义接口:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM