简体   繁体   English

如何根据 Typescript 中的参数类型声明返回类型

[英]How to declare return type based on parameter's type in Typescript

I want to infer a return type based on the parameter's type.我想根据参数的类型推断返回类型。

Here is my try这是我的尝试

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"

Link to demo 演示链接

Unfortunately I have no idea why typescript fails on line return () => arg() with an error Type '() => string' is not assignable to type 'string' where this line is in a if statement.不幸的是,我不知道为什么 typescript 在行return () => arg()上失败并出现错误Type '() => string' is not assignable to type 'string' where this line is in a if statement。

Use function overloads :使用function 过载

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");

Link to demo . 链接到演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM