【问题标题】:Props not being checked when using styled components with typescript使用带有 typescript 的样式组件时未检查道具
【发布时间】:2019-05-20 20:57:58
【问题描述】:

我正在尝试实现一个可与styled-components 一起使用的自定义组件。问题是当使用带有 typescript 的 styled-components 时,生成的 styled-component 似乎没有为它接受的 props 提供正确的类型检查。例如,假设以下是我的组件:

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

我正在尝试用 styled-components 包装它

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

【问题讨论】:

  • 无法在本地复制它,即使提供的版本相同。

标签: reactjs typescript styled-components


【解决方案1】:

您已经传递了[key: string]: string,因此invalidProp 是字符串类型的有效道具,并且也具有有效的字符串值。如果 props 是预定义的,那么您可以创建所有这些接口。这是另一个相关的question 可以帮助你。

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

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

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2020-05-01
    • 2021-03-30
    • 2019-04-13
    • 2019-10-31
    • 2019-08-20
    • 2021-12-13
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多