mog*_*rod 5 typescript reactjs typescript-generics typescript-typings
我有一个名为 React 的组件Field,用于呈现各种类型的表单输入,包括通过其他 React 组件实现的自定义输入。输入的类型由 确定type,它可以是一个已知字符串(keyof FIELD_TYPES,它反过来决定要创建的 React 组件)或任何类型的 React 组件(基于函数或类)。这已经实现了,但是我在尝试为实现提供正确的类型时遇到了一些问题。请注意,目标之一是确保正确推断道具,以便智能感知可以建议结果元素的有效属性。
这个代码沙盒展示了我正在尝试修复的 3 个不同的 Typescript 警告。每个问题都附有// FIXME注释;
(1) & (2):类型 X 不能用于索引类型 'Y' - 到目前为止,我一直无法在这里找到满足 Typescript 的方法。
(3): Typescript 不接受自定义组件 - 不确定如何修改类型以允许这样做。
我也尝试过使用区分联合,但在尝试推断组件的 props 时遇到了困难,因为它是type通过FIELD_TYPES映射传递或解决的。使用这种方法的答案也很有效。
const FIELD_TYPES = {
text: "input",
checkbox: "input",
textarea: "textarea",
custom: Custom
} as const;
type FieldTypeMap = typeof FIELD_TYPES
type KeysOfType<T, K> = { [I in keyof T]: T[I] extends K ? I : never }[keyof T]
type ReactComponentType<P = any> = React.ComponentType<P> | React.ExoticComponent<P>
type FieldTypeProps<Props = any> =
| { type?: KeysOfType<FieldTypeMap, 'input'> } & JSX.IntrinsicElements['input']
// FIXME(4): Is there any way to DRY this up?
| { type: 'textarea' } & JSX.IntrinsicElements['textarea']
| { type: 'select' } & JSX.IntrinsicElements['select']
// FIXME(5+6): How to include props for the provided react component type?
| { type: ReactComponentType<Props> } & Props // FIXME(5)
| { type: KeysOfType<FieldTypeMap, ReactComponentType<Props>> } & {} // FIXME(6)
Run Code Online (Sandbox Code Playgroud)
提前致谢!
小智 0
所以问题是您需要将自定义组件与固有输入类型分开,以便您可以映射道具。另外,因为您正在重载现有的“type”道具,所以您需要省略它。
这是现在工作的代码:https://codesandbox.io/s/typescript-inferred-react-props-forked-hrh8p ?file=/src/index.tsx
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |