问题:无状态功能组件的接口给出为
interface SFC<P = {}> {
(props: P & { children?: ReactNode }, context?: any): ReactElement<any> | null;
propTypes?: ValidationMap<P>;
}
我的组件的prop类型也是通用的:
interface Prop<V>{
num: V;
}
如何正确定义我的组件?如:
const myCom: <T>SFC<Prop<T>> = <T>(props: Prop<T>)=> <div>test</div>
这是:Typescript Playground of modified example
MyFindings:
1:Typescript 2.9.1支持有状态通用组件:http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#generic-type-arguments-in-jsx-elements
class myCom<T> extends React.Component<Prop<T>, any> {
render() {
return <div>test</div>;
}
}
2:扩展SFC以创建一个新接口,如下面的答案中所述,将使组件的prop类型为any:
Typescript React stateless function with generic parameter/return types我不想要.我想为我的道具提供合适的类型
解决方法:
你不能使用这样的泛型:
const myCom: <T>SFC<Prop<T>> = <T>(props: Prop<T>)=> <div>test</div>
TypeScript规范指出:
A construct of the form
06001
Could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter.
source; Microsoft/TypeScript spec.md
您的声明与TypeScript规范中定义的模式不匹配,因此它不起作用.
但是,您可以不使用SFC接口,只需自己声明.
interface Prop<V> {
num: V;
}
// normal function
function Abc<T extends string | number>(props: Prop<T>): React.ReactElement<Prop<T>> {
return <div />;
}
// const lambda function
const Abc: <T extends string | number>(p: Prop<T>) => React.ReactElement<Prop<T>> = (props) => {
return <div />
};
export default function App() {
return (
<React.Fragment>
<Abc<number> num={1} />
<Abc<string> num="abc" />
<Abc<string> num={1} /> // string expected but was number
</React.Fragment>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。