从组件道具中作为子项运行的类型

问题描述 投票:2回答:1

在这种情况下有没有办法获得正确的打字?

<Resource data={{ foo: 1 }}>{data => data.foo}</Resource>;
                                            ^
                                     should be number

我从没有React的简单示例开始,这很简单:

type IResult<P> = { [key in keyof P]: P[key] };
function foo<P>(
  c: (data: IResult<P>) => any,
  props: { data: P }
) {
  c(props.data);
}

foo(data => data.foo, { // `data.foo` is number
  data: { foo: 1 },
});

但是当我尝试使用与React类似的实现时,我没有运气:/

type IResult<P> = { [key in keyof P]: P[key] };

interface IRProps<T = any> {
  data: T;
  children(data: IResult<T>): React.ReactNode;
}

class Resource extends React.Component<IRProps> {
  render() {
    return this.props.children(this.props.data);
  }
}

我所能得到的只是(parameter) data: {}(parameter) data: any

我正在使用Typescript v2.6.1和React 16.2与最近的打字。

谢谢!

reactjs typescript
1个回答
0
投票

JSX和Generics有点凝聚力,所以我们必须玩一个'make typescript eat this'游戏:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.