【发布时间】:2020-03-06 03:35:08
【问题描述】:
当一个接口公开一个简单地用来输入属性的泛型时。有没有办法根据用例的推断来“使用”它?
看看这个:
请在此假设不能简单地应用 Generic,并且
onClick将存在。
如您所见,我的TestObject 的is 属性是一个泛型,它是静态给定的。有没有办法对此进行限制,所以当onClick 想要一个参数时,它知道is 属性是div,因此只允许value == 'div'。
我的用例是在 React 世界中,我希望为我的组件提供一个定义其渲染 (createElement) 的道具,但需要它对于它应用的所有处理程序和属性是类型安全的。我想泛型会起作用,但是当发送到 forwardRef 时就会崩溃。
这是我目前拥有的一个例子,也是我的困境所在。
import { AllHTMLAttributes, createElement, forwardRef } from 'react';
interface Props<Element extends keyof JSX.IntrinsicElements>
extends Omit<AllHTMLAttributes<Element>, 'width' | 'height'> {
is?: Element;
className?: string;
}
// There is a little more going on inside the Component, but you get the gist.
const Box = forwardRef<HTMLElement, Props<'div'>>(({ is, children }, ref) =>
createElement(is, {
ref,
}, children));
从那里可以看到,现在 is 属性被锁定为 div。
【问题讨论】:
标签: reactjs typescript