typescript - 类型鉴别器 - 如何限制参数
问题描述
假设我想做以下事情:
type Car = {
type: 'car'
}
type House = {
type: 'house'
}
add('car', {type: 'car'}) // < this is fine.
add('house', {type: 'car'}) // < this should cause a compile time error.
是否可以编写一个add
强制执行此约束的方法?
type
另一个要求是,您可以添加的内容没有限制。唯一的限制应该是type
s 必须匹配。
解决方案
稍微修改您的代码以使其按预期工作:
const add = <TObj extends {type: TKey}, TKey extends string>(key: TKey, obj: TObj) => {
/* ... */
}
推荐阅读
- unix - 如何通过校验和或 md5 命令验证 unix shell 脚本中的文件传输(cp、scp 命令)?
- css - 萨斯重复
html文件中具有相同内容的标签(Vue) - javascript - 如何创建一个在按钮单击事件上自动填充/填充网格的文本字段的函数。(使用反应函数组件。)
- django - 在调用前修改请求数据时,如何以编程方式从 drf 中的另一个基于类的视图调用基于类的视图?
- android - Android Gradle Kotlin Dsl 中未解决的参考问题
- android-studio - 如何通过改造进行多次通话?
- reactjs - 下一个/链接工作滞后
- javascript - 通过鼠标移动控制可变字体
- datatable - 将 Janus Grid 中的一个或多个选定行复制到 DataRowCollection 或 DataRow[]
- python - 我是否需要为 Python/MySQLdb 中的每个查询使用单独的游标?