首页 > 解决方案 > 如何在 Typescript 中根据参数类型声明返回类型

问题描述

我想根据参数的类型推断返回类型。

这是我的尝试

type Arg = string | (() => string)

function fn1(arg: Arg): typeof arg extends Function ? () => string : string {
  if (typeof arg === "function") {
    return () => arg();
  }

  return arg;
}

const a = fn1("hello") // a should be "string"
const b = fn1(() => "hello") // b should be () => "string"

演示链接

不幸的是,我不知道为什么打字稿在 if 语句中return () => arg()出现错误并在线失败。Type '() => string' is not assignable to type 'string'

标签: javascripttypescript

解决方案


使用函数重载

function fn1(arg: string): string;
function fn1(arg: () => string): () => string;
function fn1(arg: string | (() => string)){
  if (typeof arg === 'function'){
    return () => arg();
  }
  return arg;
}

const a = fn1("hello");
const b = fn1(() => "hello");

链接到演示


推荐阅读