如何允许打字稿通用参数具有默认值
我正在尝试为TS中的通用函数设置默认值。这是一个简单的示例:
type Size = "small" | "medium" | "large";
type Detail<S extends Size> = S extends "small" ? "noDetail" : S extends "medium" ? "partialDetail" : "fullDetail"
function getDetail<S extends Size>(size:S = "small"):Detail<S>{
if(size === "small")
return "noDetail" as Detail<S>;
if(size === "medium")
return "partialDetail" as Detail<S>
return "fullDetail" as Detail<S>;
}
它会导致错误:
Type '"small"' is not assignable to type 'S'.
'"small"' is assignable to the constraint of type 'S', but 'S' could be instantiated with a different subtype of constraint 'Size'.ts(2322)
我理解问题(例如:有人可以尝试 getDetail&lt;“ ligal”&gt;();
),我已经阅读了几篇文章,以便尝试并解决。
但是,
- 我不想强迫人们通过参数。
- 我想返回条件类型(不是不受约束的字符串,而不是联合)
我该怎么做?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会用您的不同值创建一个枚举,然后基于此创建您的功能。当您要求返回作为条件类型时,我还添加了一个接口,因此返回是TypeAfe:
I would create a Enum with your different values and then create your function based on that. As you requested the return as a conditional type, i also added an Interface so the return is typesafe:
我会将
添加为“小”
作为size size
的类型,并且我还将添加“ small”
作为通用类型的默认值。游乐场
I would add
"small"
as type forsize
and I would also add"small"
as default for the generic type.Playground
最好做到这一点
通过功能超载游乐场链接
This is better done with function overloads
Playground link