流类型 - 声明预期键/值类型的索引签名在 GenericType 中丢失
Flow type - Index signature declaring the expected key / value type is missing in GenericType
我在使用通用类型动态访问对象 属性 时遇到问题。这是代码:
import React, { useState } from 'react'
function useForm<FormValues>(initialValues: FormValues) {
const [formValues, setFormValues] = useState<FormValues>(initialValues)
function getValue(fieldName: string) {
return formValues[fieldName]
}
}
这是错误:
7: return formValues[fieldName]
^ Cannot get formValues[fieldName]
because an index signature declaring the expected key / value type is missing
in FormValues
[1]. References: 4: const [formValues, setFormValues]
= useState(initialValues)
^ [1]
感谢您的帮助。
让我们简化问题:
我。 useState
有以下类型:
export function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {}
二.对我们来说重要的是返回类型:
export function simpleUseState<S>(initialState: S): [S] {}
三。简化版:
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
因为 Generic 类型没有 key/value 签名,例如它可以是 number
或 null
- 我们需要在 Generic 上添加 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]
}
}
我在使用通用类型动态访问对象 属性 时遇到问题。这是代码:
import React, { useState } from 'react'
function useForm<FormValues>(initialValues: FormValues) {
const [formValues, setFormValues] = useState<FormValues>(initialValues)
function getValue(fieldName: string) {
return formValues[fieldName]
}
}
这是错误:
7: return formValues[fieldName] ^ Cannot get
formValues[fieldName]
because an index signature declaring the expected key / value type is missing inFormValues
[1]. References: 4: const [formValues, setFormValues] = useState(initialValues) ^ [1]
感谢您的帮助。
让我们简化问题:
我。 useState
有以下类型:
export function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {}
二.对我们来说重要的是返回类型:
export function simpleUseState<S>(initialState: S): [S] {}
三。简化版:
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
因为 Generic 类型没有 key/value 签名,例如它可以是 number
或 null
- 我们需要在 Generic 上添加 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]
}
}