我想了解是否有键入incript中使用tsx文件类型推断的限制。在tsx文件中的通用类型分辨率
如果我创建一个无状态的反应成分:
interface TestProps {
foo: string;
}
export const TestComp: React.StatelessComponent<TestProps> = x => {
return(<div>{foo}</div>);
};
,然后在第二TSX文件请尝试以下操作:
import { TestComp } from './TestComp';
const getProperties = function<P>(node: React.ReactElement<P>) : P {
return node.props
};
var props1 = getProperties(React.createElement(TestComp, { foo : 'bar' }));
var props2 = getProperties(<TestComp foo='bar' />);
props1将有一个推断类型的TestProps,props2会有推断类型任何。
我的印象是最后两行是相同的。 Typescript认为第二次调用中的对象是React.ReactElement<any>
有什么原因吗?
经过进一步调查,如果我将TestComp定义为正常函数而不是箭头函数'export function TestComp(props:TestProps){...}' –