流类型-在GenericType中缺少声明预期键/值类型的索引签名

时间:2019-05-17 13:03:38

标签: javascript reactjs flowtype

我在使用Generic Type动态访问对象属性时遇到问题。这是代码:

import React, { useState } from 'react'

function useForm<FormValues>(initialValues: FormValues) {
    const [formValues, setFormValues] = useState<FormValues>(initialValues)

    function getValue(fieldName: string) {
        return formValues[fieldName]
    }
}

这是错误:

  

7:返回formValues [fieldName]                             ^无法获得formValues[fieldName],因为缺少声明预期键/值类型的索引签名   在FormValues [1]中。参考:4:const [formValues,setFormValues]   = useState(initialValues)                                                    ^ [1]

这是“尝试流程”链接: https://flow.org/try/#0JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgMowoxJwC+cAZlBCHAORSoYsBQXd+AdhmAR+BYgDFoIADySoIAGooANviSEAfAApg-YDGAqlq9QC44cxSrWEAlLi4BINCMLwA2nSnGb2YjEsfdQBdOABeMVJySllva3VtXX1DZSC7LjhMuAysvkEDETgAcyQYIK06YCRlABMAORQQJHM3KF0i+xwczMd2GHwoUS95NM8q2oam4O6aLmogA

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

让问题简化:

I。 useState具有以下类型:

export function useState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {}

II。对我们来说重要的是返回类型:

export function simpleUseState<S>(initialState: S): [S] {}

III。简化版:

declare var simpleUseState: <S>(initialState: S)=> [S];

function useForm<FormValues>(initialValues: FormValues, fieldName: string) {
    const [formValues] = simpleUseState<FormValues>(initialValues)

    return formValues[fieldName];
}

我们有the same error

因为泛型类型没有键/值签名,例如它可以是numbernull-我们需要在泛型上添加constraints

import React, { useState } from 'react'

function useForm<FormValues: {[string]: string}>(initialValues: FormValues) {
//                         ^ constraint
    const [formValues, setFormValues] = useState<FormValues>(initialValues)

    function getValue(fieldName: string) {
        return formValues[fieldName]
    }
}