使用带有打字稿的样式化组件

时间:2018-12-20 10:36:48

标签: reactjs typescript styled-components

我正在尝试实现可与styled-components一起使用的自定义组件。问题在于,当使用带有TypeScript的样式化组件时,生成的样式化组件似乎无法为其接受的道具提供正确的类型检查。例如,假设以下是我的组件:

export class MyComponent extends React.Component<{identifier: string, option?: 'a' | 'b'}> {
    render() {
         const {identifier, ...props} = this.props;
         return <h1 {...props}>{identifier}</h1>
    }
}

我正在尝试将样式组件包装为

const WrappedComponent = styled(MyComponent)`
    border: 1px solid
`

现在,当我尝试将WrappedComponent呈现为

....
render() {
    return <WrappedComponent identifier="abc" />
}

Typescript引发以下错误:

Type '{ identifier: string; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<{}, never> & Partial<Pick<{}, never>>, never> & { theme?: any; } & { as?: "symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | ... 165 more ... | undefined; }'.
Property 'identifier' does not exist on type 'IntrinsicAttributes & Pick<Pick<{}, never> & Partial<Pick<{}, never>>, never> & { theme?: any; } & { as?: "symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | ... 165 more ... | undefined; }'

为什么会这样?

更新

如果我将option?: 'a' | 'b'更改为option?: string,则一切似乎都能正常工作

打字稿版本:3.2.2 样式组件版本:4.1.3 @ types / styled-components版本:4.1.4 反应版本:16.6.3 @ types / react版本:16.7.17

1 个答案:

答案 0 :(得分:0)

您已通过[key: string]: string,因此根据invalidProp是string类型的有效道具,并且还具有有效的字符串值。如果道具是预先定义的,那么您可以创建所有接口。这是另一个可以帮助您的相关question

export interface IProps {
   name: string;
   validProp: string;
   anotherValidProp: string;
}

也与此特定错误无关,但是myComponent应该是MyComponent

相关问题