typescript - 有没有办法从打字稿中的接口动态选择类型
问题描述
正如标题所说,我试图根据我在函数中收到的键从接口动态获取类型。
例子:
interface State {
foo: boolean;
bar: string;
baz: number;
}
const globalState: State = {
foo: true,
bar: 'somethin',
baz: 42,
}
const update = (key: keyof State, newValue: /* TYPE ME PLZ */): State => {
globalState[key] = newValue;
return globalState;
}
不幸的是,这会导致错误Type '<INSERTED_TYPE>' is not assignable to type 'never'
我得到的最接近的是这样的State[keyof State]
,但它与我在函数中收到的密钥完全无关。
我的问题:有没有办法获取newValue
参数的类型?
额外问题:为什么错误消息中的类型是never
?
解决方案
推荐阅读
- kubernetes - 如何将自定义 DNS 与 cluster.local 一起用于 kubernetes
- database - How to find mongodb document by id without a search?
- google-bigquery - 使用循环在大查询中自动创建变量序列
- kubernetes - Spinnaker:管理员登录页面上出现意外的令牌“<”
- javascript - 将动态 HTML 表中的数据保存到 MySql 数据库
- node.js - 你可以使用嵌入随机小狗 url 函数的 discord.js
- ios - 如何使用 Swift 在 Tableview Cell 中添加 UITableview
- python - 如何在 Tkinter 窗口中显示文本变量?
- angular - D3 Pie Legend 未显示
- html - 列表的 CSS 不适用于 Bootstrap 4