You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TypeScript拒绝接受永远不会返回的函数返回类型?

让TypeScript对函数未使用的返回类型分支发出警告

TypeScript默认不会对这种情况发出警告,因为返回number属于number|PinkUnicorn的合法子类型。要实现你需要的检测,可以通过以下两种方式:

方法一:使用ESLint的TypeScript插件规则

借助@typescript-eslint/no-unused-types规则,它能检测到返回类型中从未被实际返回的分支。

  1. 确保已安装依赖:

    npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser
    
  2. 在ESLint配置文件(如.eslintrc.js)中启用该规则:

    module.exports = {
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      rules: {
        '@typescript-eslint/no-unused-types': [
          'warn',
          {
            ignoreArgs: false,
            ignoreVars: false,
            ignoreProperties: false,
            ignoreClasses: false,
          },
        ],
      },
    };
    

配置完成后,ESLint会针对你的示例代码提示PinkUnicorn类型在返回类型中未被使用,触发警告。

方法二:纯TypeScript编译时约束

如果不想依赖ESLint,可以通过自定义类型工具强制函数的实际返回类型与声明的返回类型完全匹配:

首先定义一个用于判断类型完全相等的工具类型:

type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends
  (<T>() => T extends Y ? 1 : 2) ? true : false;

接着创建约束类型,确保函数的实际返回值类型和声明的返回类型完全一致:

type EnforceExactReturnType<Fn extends (...args: any[]) => any, ExpectedReturn> =
  Equal<ReturnType<Fn>, ExpectedReturn> extends true ? Fn : never;

// 使用示例
type PinkUnicorn = { type: 'pink-unicorn' };

const giveNumber: EnforceExactReturnType<() => number, number | PinkUnicorn> = () => {
  return 42; // TypeScript编译报错:类型'() => number'不能赋值给类型'never'
};

这种方式会在编译阶段直接报错,提示实际返回类型与声明的返回类型不匹配。

内容的提问来源于stack exchange,提问作者RustyNova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:09:17