代码之家  ›  专栏  ›  技术社区  ›  Jordi Nebot Roberto Zvjerković

如何从接口中使用的所有类型中引用任何类型?

  •  0
  • Jordi Nebot Roberto Zvjerković  · 技术社区  · 6 年前

    给定以下代码:

    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 作为 value 的类型在函数签名中,用于引用我的接口中使用的任何类型的更通用的东西?我猜 typeof keyof IElementWithAttrs 似乎不成立。。。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Jordi Nebot Roberto Zvjerković    6 年前
    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'.
    
    推荐文章