Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 传输流/类型脚本后保留类型检查_Javascript_Node.js_Typescript_Flowtype - Fatal编程技术网

Javascript 传输流/类型脚本后保留类型检查

Javascript 传输流/类型脚本后保留类型检查,javascript,node.js,typescript,flowtype,Javascript,Node.js,Typescript,Flowtype,当前,如果我从以下内容编译一个flow/typescript文件 // @flow function foo(x: number): string { if (x) { return String(x); } return "default string"; } module.exports = foo; 对下列事项: function foo(x ) { if (x) { return Stri

当前,如果我从以下内容编译一个flow/typescript文件

// @flow

function foo(x: number): string {
    if (x) {
        return String(x);
    }
    return "default string";
}

module.exports = foo;
对下列事项:

function foo(x        )         {
    if (x) {
        return String(x);
    }
    return "default string";
}

module.exports = foo;
我的问题是,有没有一种方法可以将代码转换成下面这样的内容

function foo(x) {
    // preserve typechecking
    if (typeof x !== "number")
        throw new Error(`Expected x to be of type <number> instead got <${typeof x}>!!!!`);

    if (x) {
        return String(x);
    }
    return "default string";
}
函数foo(x){ //保留类型检查 如果(x的类型!=“编号”) 抛出新错误(`预期x的类型为而不是GET!!!!`); if(x){ 返回字符串(x); } 返回“默认字符串”; }
不幸的是,Microsoft团队决定不在编译后使用保留类型检查,因为这违背了他们的设计目标。这是GitHub上的一个应用程序

在“非目标”部分#5中,它将不会添加/依赖此功能

但是,在计数时添加参数类型检查并不太困难

function printMessage(message: string) { if (typeof message != "string") throw new Error("printMessage(message): message must be a string."); else { console.log(message); } } 函数printMessage(消息:字符串){ 如果(消息类型!=“字符串”) 抛出新错误(“printMessage(message):消息必须是字符串。”); 否则{ 控制台日志(消息); } }
我想指出的是,这并不是javascript故意设计用来做的事情。与谷物作战有时会带来更多的麻烦。

这会很快中断,因为它无法与接口一起工作,因此只能带来有限的好处。@DanielHilgarth同意,编译器可以逐个插入代码来检查接口的一致性,但运行时的影响会使其不可用,因此毫无价值。您可以创建一个编译器转换来实现这一点。在代码中添加类型检查原语,但不要认为已经为此构建了一些东西@david sherret这样做是因为你可以从中获得灵感