typescriptreact-window

How to type the index and style props passed to Row function using React-Window


I am trying to type the following two parameters passed to Row function.

//https://github.com/bvaughn/react-window

import * as React from "react";
import styled from "styled-components";
import { FixedSizeList as List } from "react-window";
import AutoSizer from "react-virtualized-auto-sizer";

const StyledSection = styled.section`
  width: 100vw;
  height: 100vh;
  background: #C0C0C0;
`;

const Row = ({ index, style }) => (
  <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
    Row {index}
  </div>
);

const Scroller = () => {
  return (
    <StyledSection>
      <AutoSizer>
        {({ height, width }) => {
          return (
            <List height={height} width={width} itemSize={20} itemCount={300}>
              {Row}
            </List>
          );
        }}
      </AutoSizer>
    </StyledSection>
  );
};

export { Scroller };

So the following snippet of code typescript infers the index and style parameters as type any. I tried to inline the type for index as number but then the compiler says index is not defined.

   const Row = ({ index, style }) => (
      <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
        Row {index}
      </div>
    );

Any ideas how to provide types to these two paramaters. react-window has its own d.ts file. Here is the working codesandbox - https://codesandbox.io/s/infinite-scroller-52b7d?file=/src/Scroller.tsx


Solution

  • Is this what you seek for?

    import { CSSProperties } from 'react';
    
    const Row = ({ index, style }: { index: number; style: CSSProperties; }) => (
      <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
        Row {index}
      </div>
    );
    

    You can still add typing when using object destructuring. Also you can use your IDE to find the type of style, using goto declaration on the first style of style={style}. (ctrl-b or ctrl-q in jetbrain IDE, doesn't know for VScode, sorry).