首页 > 解决方案 > 如何从接口中使用的所有类型中引用任何类型?

问题描述

给定以下代码:

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 | Zasvalue类型更改为更通用的东西,它指的是我的界面中使用的任何类型?我的猜测typeof keyof IElementWithAttrs似乎不成立...

标签: typescript

解决方案


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'.

推荐阅读