typescript - 如何从接口中使用的所有类型中引用任何类型?
问题描述
给定以下代码:
interface IElementWithAttrs {
someAttrA: X
someAttrB: Y
someAttrC: Z
}
const getModifiedElement = (element: IElementWithAttrs, attr: keyof IElementWithAttrs, value: X | Y | Z): IElementWithAttrs => {
return {...element, [attr]: value}
}
如何将函数签名中的X | Y | Z
asvalue
类型更改为更通用的东西,它指的是我的界面中使用的任何类型?我的猜测typeof keyof IElementWithAttrs
似乎不成立...
解决方案
interface IElementWithAttrs {
someAttrA: string
someAttrB: number
someAttrC: boolean
}
const modifyElement = <K extends keyof IElementWithAttrs>(
element: IElementWithAttrs,
attr: K,
value: IElementWithAttrs[K]
): IElementWithAttrs => {
return { ...element, [attr]: value }
}
modifyElement(null, 'someAttrA', 1); // Argument of type '1' is not assignable to parameter of type 'string'.
推荐阅读
- intershop - 应用程序之间意外的购物篮共享
- android - 颤振)图标的状态不能立即改变(编辑)
- c# - 需要在 Windows 启动时从 WPF UI 设置控制台应用程序
- javascript - 无法运行护照登录策略。身份验证错误~ TypeError: Cannot read property 'authenticate' of undefined
- layout - 是否可以在 2 个视图之间创建一个边界,以便它们的 z-index 始终彼此相邻?
- python - 如何为两支球队的比赛找到最佳解决方案?
- javascript - 即使启用按钮后,反应引导模式按钮也不会触发 onClick 方法
- python - 为什么 Popen('ping URL').communicate() 在 Windows 中有效而在 Ubuntu 中无效?
- c# - 使用 C# 从 AWS 上的 S3 读取 Avro 数据
- elasticsearch - 将 geoIP 数据添加到 Elasticsearch 索引中的旧数据