typescript - Typescript 避免为泛型类型提供参数
问题描述
假设我有一些通用类型
type Foo<T = string, U = number> = {
t: T
u: U
}
T 和 U 都不是必需的。我怎样才能提供 U 而不是 T。
理想情况下,我可以做类似的事情
type G = Foo<,string> // expected syntax
// expected result
type G = {
t: string;
u: string;
}
我尝试过的事情:
type G = Foo<never, string> // ❌
type G = Foo<unknown, string> // ❌
type G = Foo<Foo['t'], string> // ❌ (Works in this exact example but not in the general case. I want to extract the first default parameter type rather than extracting out the resulting `t`).
解决方案
如果您可以DefaultType
预先定义并null
作为“可选”第一个参数传递,这可以工作:
type DefaultType = number;
type Foo<T, U = number> = T extends null ? {
t: DefaultType
u: U
} : {
t: T
u: U
}
type h = Foo<null,string>
const newVar:h = {
t: 1,
u: "123"
}
type h1 = Foo<string,string>
const newVar1: h1 = {
t: "string",
u: "string"
}
推荐阅读
- python - Python服务器从所有连接的客户端获取recv,而不仅仅是从第一个连接的客户端
- json - Scala 解析非规范 JSON
- javascript - NextJS getStaticProps 没有将返回的道具传递给页面
- mysql - 如何使用 group_concat 和左连接对 mysql 查询的结果进行计数
- mongodb - 为正在运行的 MongoDB 容器添加索引
- substrate - 区块未在专用网络中完成
- ruby-on-rails - Heroku上每天大约同一时间奇怪的postgres慢查询
- java - 按图案排序
- r - ggplot的变化分区图
- python-3.x - TypeError:不支持的操作数类型 -:'str' 和 'str',帮帮我