[英]How to make a React Function infer a typescript type?
I'm kinda new to typescript, I cannot say that I'm loving it, but as I'm doing a library it was a good idea to test it a little more.我对 typescript 有点陌生,我不能说我喜欢它,但是当我在做一个图书馆时,多测试一下是个好主意。
I'm having a problem typing a Function, I tried with generic types with no success.我在输入 Function 时遇到问题,我尝试使用泛型类型但没有成功。 Basically, I have a component that receives a list
and an onRender
function.基本上,我有一个接收list
和onRender
function 的组件。
import React from 'react';
export default function Iterator<ItemsOnListType>(
props: IteratorPropTypes<ItemsOnListType>,
) {
const { list, onRender } = props;
return <>{list.map(onRender)}</>;
}
Its types:其类型:
interface IteratorPropTypes<T> {
list: Array<T>;
onRender: (prop: T, index: number, originalList: Array<T>) => JSX.Element;
}
But, on its test file, the prop and index are not typed, they show any
type.但是,在其测试文件中,prop 和 index 没有输入,它们显示any
类型。 I want a good fix for this problem, I'm probably missing something, I basically want that onRender props work like the Array.map
function that can infer its type from the array.我想很好地解决这个问题,我可能遗漏了一些东西,我基本上希望 onRender 道具像Array.map
function 一样可以从数组中推断出它的类型。 The code is available here https://github.com/WilliamCSA04/React-Useful-Components/tree/master/src/components/Iterator代码可在此处获得 https://github.com/WilliamCSA04/React-Useful-Components/tree/master/src/components/Iterator
Thank you.谢谢你。
From what I see, you just forget to export your type and import it in Iterator.tsx.据我所知,您只是忘记导出类型并将其导入 Iterator.tsx。 Although there is no error, IteratorPropTypes
is actually pointing to global namespace which is not correct.虽然没有错误,但IteratorPropTypes
实际上指向的是不正确的全局命名空间。
Iterator.type.ts迭代器.type.ts
export interface IteratorPropTypes<T> { // export type
list: Array<T>;
onRender: (prop: T, index: nzumber, originalList: Array<T>) => JSX.Element;
}
Iterator.tsx迭代器.tsx
import React from 'react';
import { IteratorPropTypes } from './Iterator.types'; // import type
export default function Iterator<ItemsOnListType>(
props: IteratorPropTypes<ItemsOnListType>,
) {
const { list, onRender } = props;
return <>{list.map(onRender)}</>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.