So I just encountered a problem where I want to make a better type checking in a
props of a React component. It’s about one
prop takes an array of certain type X, and in another
prop: callback, this type X needs to be the parameter of the callback. Let’s see how to do that in TypeScript.
T means here we take a generic type
T and use it through this
itemsis an array of type
- the first parameter of
In order to share type between these two
props, we need to have this type
T declared at the interface level, this is why wen have that
Now things become interesting because when you apply this
IDropDownProps<T> to a component, you
MUST declare what this
Now we need to declare the React component which takes this
IDropDownProps as its
it’s just as easy as
class DropDown<T> extends React.Component<IDropDownProps<T>>.
With the introduction of
function component will be the future of React. and remember the name
function component, now it’s been unified to this name compare to the
stateless functional component, even in the latest version of
@types/react, now you can use
Don’t know how to use it with a component been declared like this:
Feel free to comment if you know how.
We just declared the component, now we need to use it, the problem is, when we use a component, most of the time, we use
JSX syntax. With Typescript 2.9, generic type in JSX syntax is possible.
So, you just use it like this:
Now, if you pass a wrong callback like this:
The compiler will complain that the expected type for
string where you declare it as a
Hope it helps. :)