簡體   English   中英

如何找到這種 TS 類型(React 和 final-form 的示例)?

[英]How this TS type is found (example with React and final-form)?

我不明白在這個例子中一個類型是如何計算的(這是 React 的最終形式 npm,如果這與它們有關):

這是我的片段( 在 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;

好的,這綁定到 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" ,接口采用 2 個泛型,它們都是可選的,並且默認為 Element 類型。

interface FocusEvent<Target = Element, RelatedTarget = Element> extends SyntheticEvent<Target, NativeFocusEvent> {
    relatedTarget: (EventTarget & RelatedTarget) | null;
    target: EventTarget & Target;
}

所以在我的代碼中,由於沒有第二個泛型傳輸,結果類型是:

React.FocusEvent<HTMLInputElement, Element> | undefined) => void;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM