【发布时间】:2017-11-18 06:36:26
【问题描述】:
无需了解 React,只需了解一些背景知识:在我的用例中,我想用我的自定义高阶组件来放大用户指定的 React.ComponentClass。为此,我希望用户还向我发送我的高阶组件将注入的特定道具的名称列表。可以这样完成:
function listToComponentProps<TComponentProps, TKey = keyof TComponentProps>(props: Array<TKey>) {
// Logic here, not important for the example
}
interface TestProps {a: number, b: Function, c: () => number}
listToComponentProps<TestProps>(['a', 'b', 'c'])
keyof 关键字为我处理约束。
listToComponentProps<TestProps> 的示例输入为
- 有效:
['b']、['b', 'c']、['c'] - 无效
-
['a']、['a', 'b']、['a', 'b', 'c'](a 是数字,而不是函数) -
['d'],['d', 'c'](d 不是接口的一部分TestProps
-
问题是,我想限制props参数不仅是TComponentProps的键,还要限制TComponentProps中对应类型为Function的键(这样'a'就会是打字稿编译器检测到的无效选项)。怎样才能完成这样的任务?
【问题讨论】:
-
您应该知道用户可以使用此设置执行
listToComponentProps<TestProps, "a" | "b" | "c" | "d">(['a', 'b', 'c', 'd'])。TComponentProps和TKey实际上都没有在这里相互限制。 -
是的,我知道这一点。但是,高阶组件的用户将无法直接访问该函数,listToComponentProps 将只是一个内部函数。
标签: typescript types