我不明白在这个例子中类型是如何计算的(如果这与最终形式npm相关,这是React with final form npm):
这是我的代码片段(test it on TS playground):
import * as React from 'react';
interface FieldInputProps<FieldValue, T extends HTMLElement> {
name: string;
onBlur: (event?: React.FocusEvent<T>) => void;
onChange: (event: React.ChangeEvent<T> | any) => void;
onFocus: (event?: React.FocusEvent<T>) => void;
type?: string;
value: FieldValue;
checked?: boolean;
multiple?: boolean;
}
export interface FieldRenderProps<FieldValue, T extends HTMLElement> {
input: FieldInputProps<FieldValue, T>;
}
interface Props {
field: FieldRenderProps<string, HTMLInputElement>;
mask?: "number" | "percent" | undefined;
style?: any;
}
function CellInput({
field: {
input: { value, onChange, ...inputProps }, // Problem here on the inputProps type
},
mask,
style,
}: Props) {
const onFocus = inputProps.onFocus
// Why onFocus signature is : onFocus: (event?: React.FocusEvent<HTMLInputElement, Element> | undefined) => void;
// What I expect : onFocus: (event?: React.FocusEvent<T>) => void;
}我不明白为什么我的变量inputProps有这个onFocus签名:
它是onFocus: (event?: React.FocusEvent<HTMLInputElement, Element> | undefined) => void;。
我期望的是:onFocus: (event?: React.FocusEvent<T>) => void;
发布于 2021-10-12 13:04:15
好的,这被绑定到React类型FocusEvent:
之前,在我的应用程序中,我使用了@types/react": "16.9.25",,它具有:
interface FocusEvent<T = Element> extends SyntheticEvent<T, NativeFocusEvent> {
relatedTarget: EventTarget | null;
target: EventTarget & T;
}现在,在"@types/react": "^17.0.28"中,接口接受两个泛型,它们都是可选的,并且默认元素类型。
interface FocusEvent<Target = Element, RelatedTarget = Element> extends SyntheticEvent<Target, NativeFocusEvent> {
relatedTarget: (EventTarget & RelatedTarget) | null;
target: EventTarget & Target;
}因此,在我的代码中,由于没有传递第二个泛型,因此结果类型为:
React.FocusEvent<HTMLInputElement, Element> | undefined) => void;https://stackoverflow.com/questions/69539882
复制相似问题