打字稿返回分配函数的推断类型,但限制返回类型以扩展预定义类型

埃利亚夫·卢斯基

我正在编写许多函数(用于服务器请求),每个函数返回类型都扩展了某种类型。
我希望打字稿限制返回类型以扩展预定义的已知类型,但我希望打字稿采用返回类型的推断类型(因为它可能更准确)。

例如,假设所有函数都必须返回字符串,因此:

type myFuncsType = (...args: any) => string

每个函数都必须扩展这种类型。

现在可以说我的函数总是返回一个常量字符串:

const myFunc1 = () => "MyString" as const
// the type is inffered:
const myVal = myFunc1()
// typeof myVal = "MyString"

我们还说过我们的函数必须扩展预定义的已知类型(myFuncsType),但是在分配类型时,通用类型会接管推断出的准确类型,这是我想避免的:

const myFunc1: myFuncsType = () => "MyString" as const
const myVal = myFunc1()
// typeof myVal = string

我尝试用泛型解决它,但泛型需要传递预定义类型,并且在声明期间返回类型不可用。

如何限制返回类型以扩展预定义类型,但又返回从声明中推断出的确切返回类型?

杰卡兹

由于MyFuncsType不是union,如果您使用myFunc1类型注释变量,编译器将始终将该变量视为该类型。它不会根据分配给它的特定值来缩小变量的范围,而是将其一直扩大到带注释的类型。所以你不想注释myFunc1

相反标注的,你真正想要做的是检查myFunc1是分配给MyFuncsType,没有扩大它。在 TypeScript 中没有内置的操作符来做到这一点;有关此类功能的请求,请参阅microsoft/TypeScript#7481但是您可以编写自己的辅助函数,其行为方式如下:

type MyFuncsType = (...args: any) => string
const asMyFuncsType = <T extends MyFuncsType>(t: T) => t;

所以代替const f: MyFuncsType = ...,你写const f = asMyFuncsType(...)asMyFuncsType()函数仅返回其输入而不更改其类型,但它会检查该类型是否可分配给MyFuncsType,因此它会捕获错误:

const badFunc = asMyFuncsType(() => 123); // error!
// -------------------------------> ~~~
// Type 'number' is not assignable to type 'string'

const myFunc1 = asMyFuncsType(() => "MyString" as const); // okay
const myVal = myFunc1()
// typeof myVal = "MyString"

Playground 链接到代码

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章