How to type a styled component without losing any prop with Typescript?

前端 未结 3 2028
囚心锁ツ
囚心锁ツ 2021-01-06 16:00

I\'m new to styled components and I\'d like to be able to type my styled components correctly so that when I pass props \"vs code\" I can autodetect all those props I have,

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 16:50

    For some reason (possibly due to the way styled-components's typescript definition is written), the typing for Theme works if you remove one of level of nesting. This snippet typechecks with no error for me (v4) i.e. typescript knows that primaryColor is a string:

    const theme = {
      primaryColor: '#FF5018',
      secondaryColor: '#252729',
      tertiaryColor: '#1A1C1E',
      textColor: 'white',
    };
    
    type Theme = typeof theme;
    
    type Props = Theme & {
      // ... other keys
    }
    
    const NavigationBarStyled = styled.div`
      grid-area: navigation-bar-item;
      padding-left: 2rem;
      display: flex;
      align-items: center;
      color: ${props => props.primaryColor};
      background-color: ${props => props.primaryColor};
    `;
    

提交回复
热议问题