gpt4 book ai didi

typescript - tsx 文件中的通用类型解析

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:48 24 4
gpt4 key购买 nike

我试图了解在 typescript 中使用 tsx 文件进行类型推断是否存在限制。

如果我创建一个无状态的 React 组件:

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 将具有any 的推断类型。

我的印象是最后两行是等价的。 Typescript 认为第二次调用中的对象是 React.ReactElement<any> 是否有原因? ?

最佳答案

这里只是一些语法混淆。你的箭头函数没有按照你的想法去做:

export const TestComp: React.StatelessComponent<TestProps> = x => {
return(<div>{foo}</div>);
};

x 类型为any。此外,函数中甚至没有使用 x。你真正想要的是:

export const TestComp: React.StatelessComponent<TestProps> = (x: TestProps) => {
return(<div>{x.foo}</div>);
};

顺便说一句,关于箭头函数的快速风格说明:我通常只在不得不使用 bind 时才使用箭头函数。在这个简单的示例中,我实际上更喜欢使用普通函数,因为 this 没有任何时髦的事情发生。

关于typescript - tsx 文件中的通用类型解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com