首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个TS类型是如何找到的( React和final-form的例子)?

这个TS类型是如何找到的( React和final-form的例子)?
EN

Stack Overflow用户
提问于 2021-10-12 11:41:19
回答 1查看 65关注 0票数 0

我不明白在这个例子中类型是如何计算的(如果这与最终形式npm相关,这是React with final form npm):

这是我的代码片段(test it on TS playground):

代码语言:javascript
复制
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;

EN

回答 1

Stack Overflow用户

发布于 2021-10-12 13:04:15

好的,这被绑定到React类型FocusEvent:

之前,在我的应用程序中,我使用了@types/react": "16.9.25",,它具有:

代码语言:javascript
复制
interface FocusEvent<T = Element> extends SyntheticEvent<T, NativeFocusEvent> {
    relatedTarget: EventTarget | null;
    target: EventTarget & T;
}

现在,在"@types/react": "^17.0.28"中,接口接受两个泛型,它们都是可选的,并且默认元素类型。

代码语言:javascript
复制
interface FocusEvent<Target = Element, RelatedTarget = Element> extends SyntheticEvent<Target, NativeFocusEvent> {
    relatedTarget: (EventTarget & RelatedTarget) | null;
    target: EventTarget & Target;
}

因此,在我的代码中,由于没有传递第二个泛型,因此结果类型为:

代码语言:javascript
复制
React.FocusEvent<HTMLInputElement, Element> | undefined) => void;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69539882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档