javascript - 如何在 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'
解决方案
推荐阅读
- javascript - 如何使用javascript在段落上应用选定的边框样式
- python - 检查数字是否为素数,Python抛出异常
- c# - Entity Framework Core:使用自动生成的外键作为复合主键的一部分
- python - 在 python azure web 应用程序中将数千个 blob 文件从容器移动到另一个容器的最快方法?
- if-statement - 如何在我的 if 语句中触发画布图像上的 SetActive - 一旦拾取对象以在 UI 画布系统中显示该对象?
- python - 使用 python 解决非线性动力学问题的最佳方法是什么?
- javascript - 带有父子的Vue表单转发器
- javascript - 如何检查列表是否包含在javascript中传递的元素
- java - MacBook M1 上的 Java JDK
- reactjs - 突出显示所选项目 onPress