不用打字稿有什么好处

Sun*_*arg 5 typescript

我刚从打字稿开始,从未读过有关打字稿的文章。但是我没有得到它的实际目的。从这个

我知道,任何将不执行或无法访问的代码都标记为从不

// Type () => never
const sing = function() {
    while (true) {
        console.log("Never gonna give you up");
        console.log("Never gonna let you down");
        console.log("Never gonna run around and desert you");
        console.log("Never gonna make you cry");
        console.log("Never gonna say goodbye");
        console.log("Never gonna tell a lie and hurt you");
    }
};
Run Code Online (Sandbox Code Playgroud)

上面代码中的函数有一个无限循环,因此将被标记为“永不”,那么这样做的好处是什么?

Rod*_*ris 5

对于您的示例,好处是保证您不会从函数中创建转义符。

尝试显式设置never返回类型。

const sing = function():never {
    while (true) {
        console.log("Never gonna give you up");
        console.log("Never gonna let you down");
        console.log("Never gonna run around and desert you");
        console.log("Never gonna make you cry");
        console.log("Never gonna say goodbye");
        console.log("Never gonna tell a lie and hurt you");

        break; // Error
    }
};
Run Code Online (Sandbox Code Playgroud)


小智 1

Typescript 中有一些“Never”关键字的用例。

\n

当您确定某件事永远不会发生时,使用 never 类型。

\n

\xe2\x9c\x85 保护子句:它强制你检查所有可能的情况。

\n

\xe2\x9c\x85 函数永远不会返回任何内容。它一直都有事情要做(不定式循环)

\n

\xe2\x9c\x85 函数总是抛出错误。

\n
// 1) Guard Clauses (forces you to check all possible cases)\ntype CurrencyOptions = "EURO" | "USD" | "AZN"\n\n    function getRate(currency: CurrencyOptions) {\n    switch (currency) {\n        case "EURO":\n            return 1.80\n        case "USD":\n            return 1.70\n        case "AZN":\n            return 1.20\n        default:\n            const _unreachable: never = currency  // will get Type Error if you remove one of the cases \n            throw "Not found"\n    }\n}\n\n\n\n// 2) function will Throw error\n\nfunction throwError(errorMsg: string): void {\n    throw new Error(errorMsg);\n}\n\n\n\n// 3) function will Never end\nfunction keepProcessing(): never {\n    while (true) console.log('Never ends.')\n}\n
Run Code Online (Sandbox Code Playgroud)\n

nevervoid之间的主要区别在于:

\n

Void - 函数不返回任何内容或显式返回未定义。

\n

从不- 函数根本不返回任何内容。

\n