【问题标题】:TypeScript: How to set a const variable in a try block?TypeScript:如何在 try 块中设置 const 变量?
【发布时间】:2021-01-06 17:04:17
【问题描述】:

我想声明一个const 变量,在try 块内对其进行初始化,然后在该try 块之外使用它。例如:

const result;

try {
    result = getResult();
} catch (error) {
    report(error);
    return;
}

use(result);

或异步:

const result;

try {
    result = await fetchResult();
} catch (error) {
    report(error);
    return;
}

use(result);

我不想要的:

  • 使用let,因为这允许以后覆盖result
  • 将其移至单独的函数,因为我只希望在给定范围内可以访问此逻辑。

我在我的代码中经常看到这种模式,那么有没有办法使用模块化 TypeScript 解决方案来做到这一点?

以下问题类似,但不提供可重用的类型安全解决方案:

【问题讨论】:

  • 如果抛出错误,catch下面的代码永远不会被使用。为什么不直接将后续代码放在 try 中?
  • @crashmstr 因为catch 下面的代码也可能抛出,这可能需要不同的错误处理。因此,将所有内容放在同一个 try 块中可能会导致意外行为。

标签: typescript error-handling


【解决方案1】:

同步解

使用以下类型安全的实用函数:

function tryGet<T>(getter: () => T): {
    success: true;
    value: T;
} | {
    success: false;
    error: Error;
} {
    try {
        return {
            success: true,
            value: getter(),
        };
    } catch (error) {
        return {
            success: false,
            error: error as Error,
        };
    }
}

用法:

import { report, use } from './imagination';

const result = tryGet(getValue);

if (!result.success) {
    report(result.error);
    return;
}

use(result.value);

异步解决方案

export default async function tryGetAsync<T>(
    getter: () => Promise<T>
): Promise<{
    success: true;
    result: T;
} | {
    success: false;
    error: Error;
}> {
    try {
        return {
            success: true,
            result: await getter(),
        };
    } catch (error) {
        return {
            success: false,
            error: error as Error,
        };
    }
}

用法:

import { report, use } from './imagination';

const result = await tryGetAsync(fetchValue);

if (!result.success) {
    report(result.error);
    return;
}

use(result.value);

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2014-06-23
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多