typescript - 函数具有显式返回时的窄推断类型
问题描述
看下面的代码:
type Shape = null | string | string[] | { [key: string]: string | string[] }
interface ICfg<InShape extends Shape, OutShape extends Shape> {
shapes?: readonly [InShape, OutShape]
handle?(x: NonNullable<this["shapes"]>[0]): NonNullable<this["shapes"]>[1]
}
function apply<InShape extends Shape, OutShape extends Shape>(cfg: () => ICfg<InShape, OutShape>) {
return cfg()
}
const shape = {
type: "abc",
date: "qwe",
}
var x = apply(() => ({
shapes: [shape, shape],
handle: x => null as any,
}))
变量x
的类型是ICfg<{ type: string; date: string; }, { type: string; date: string; }>
完美的。
但是让我们稍微改变一下函数语法: from () => ({ ... })
to () => { return { ... } }
:
var y = apply(() => {
return {
shapes: [shape, shape],
handle: x => null as any,
}
})
现在的类型y
是ICfg<Shape, Shape>
,这很糟糕。
实际上我有更多的困难,因为我真的需要变量shape
在函数内部(实际上函数apply
有参数并且shape
基于它们):
var z = apply(() => {
const shape = {
type: "abc",
date: "qwe",
}
return {
shapes: [shape, shape],
handle: x => null as any,
}
})
此代码ICfg<Shape, Shape>
对变量产生相同的结果z
。
我需要变量z
来拥有ICfg<{ type: string; date: string; }, { type: string; date: string; }>
像x
这样的类型。有没有办法在没有明确指定泛型参数的情况下实现这一点apply
?
解决方案
推荐阅读
- javascript - 从 Javascript 中的 PHP 数组填充 Google GeoChart 地图的问题
- postgresql - 维护具有完全相同架构的开发数据库
- java - 为什么 JsonParser 在返回值中使用双引号,使用 com.google.gson API
- python - 如何在 Python 中使用 Android 的“IP 网络摄像头”应用程序
- c++ - 我将如何获得正确的公式结构以在我的程序 C++ 中获得 c 面?
- php - Laravel 软删除原始查询问题
- python - 如果任何列包含其中一个关键字,则删除行
- kotlin - 我可以用 Kotlin 将一行也语法转换成两行吗?
- jquery - Fullcalender 启用特定日期范围
- electron-vue - 我对电子 vue 有疑问,我需要一个解决方案