类型'{}'不能赋值为'IntrinsicAttributes&IntrinsicClassAttributes

S. *_*. N 17 json typescript reactjs

我目前正在做一个简单的反应应用程序.这是我的index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <App />,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();
Run Code Online (Sandbox Code Playgroud)

在这里,我有我的 app.tsx

    import * as React from 'react';
import SearchBar from '../containers/price_search_bar';

interface Props {
  term: string;
}

class App extends React.Component<Props> {

  // tslint:disable-next-line:typedef
  constructor(props) {
    super(props);
    this.state = {term: '' };
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          this is my application.
        </p>
        <div>
            <form>
            <SearchBar term={this.props.term} />
            </form>
        </div>
      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

还有我的搜索栏容器:

    import * as React from 'react';

interface Props {
    term: string;
}

// tslint:disable-next-line:no-any
class SearchBar extends  React.Component<Props> {

    // tslint:disable-next-line:typedef
    constructor(props) {
        super(props);
        this.state = { term: '' };
    }

    public render() {
        return(
            <form>
                <input 
                    placeholder="search for base budget"
                    className="form-control"
                    value={this.props.term}
                />
                <span className="input-group-btn" >
                    <button type="submit" className="btn btn-secondary" >
                        Submit
                    </button>
                </span>

            </form>
        );
    }
}

export default SearchBar;
Run Code Online (Sandbox Code Playgroud)

最后我有我的tsconfig.json:

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "noUnusedLocals": true
  },
  "exclude": [
    "node_modules",
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我一直在错误后得到不同的错误,当我修复一个错误时,另一个出现,我不知道我做了什么让它表现得像这样.这是最新的错误:

./src/index.tsx
(7,3): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<App> & Readonly<{ children?: ReactNode; }> & Reado...'.
  Type '{}' is not assignable to type 'Readonly<Props>'.
    Property 'term' is missing in type '{}'.
Run Code Online (Sandbox Code Playgroud)

我试图通过修改我来修复它,tsconfig.json但仍然出现相同的错误,我做错了什么以及为什么打字稿就像这样.我对此非常陌生,通过这个例子,我正在尝试udnertand反应如何一起工作.

CPH*_*hon 104

我只是通过声明一个完全传递给组件的对象,解决了很多“无法分配到类型 'IntrinsicAttributes & IntrinsicClassAttributes ” 类型的错误(Microsoft 已关闭问题)。

使用 OP 的示例,而不是使用term={this.props.term},使用{...searchBarProps}使其工作:

render() {
  const searchBarProps = { // make sure all required component's inputs/Props keys&types match
    term: this.props.term
  }
  return (
    <div className="App">
      ...
      <div>
          <form>
          <SearchBar {...searchBarProps} />
          </form>
      </div>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这可能会解决错误,但这确实是不好的做法。您应该具体说明传递给组件的 props (18认同)
  • 天啊,我这几天一直在想办法解决这个问题。你是一个救星。 (4认同)
  • 善良。我希望这没有必要。 (4认同)
  • @ZunaibImtiaz 深入研究 [Typescript 的 _checker.ts_](https://github.com/microsoft/TypeScript/blob/master/src/compiler/checker.ts) 它的工作原理很可能是因为对 `intrinsicAttributes` 进行赋值的块不需要执行,因为没有显式的 _JsxAttributes_ 来比较该组件的调用(`isComparingJsxAttributes` 可能是假的)。如果您确实需要了解情况是否如此,请尝试调试 Typescript 的源代码。 (3认同)
  • 你拯救了我的职业生涯,哈哈,谢谢你 (3认同)
  • 善良。你是一个救星! (2认同)
  • @JonWyatt 在某些情况下,组件本身就是问题:我在 2019 年使用 3rd-party-lib ([AntD](https://ant.design)) 时第一次遇到这个问题,即使我们正确通过,错误也会出现所有必需的道具。 (2认同)

Swa*_*nil 16

这里的问题不在于您的 tslint 设置。看下面的代码片段:

interface SearchBarProps {
  term: string;
  optionalArgument?: string;
}

interface SearchBarState{
  something: number;
}

class SearchBar extends React.Component<SearchBarProps, SearchBarState> {
  constructor(props: SearchBarProps){
    super(props);

    this.state = {
      something: 23
    };
  }

  render() {
    const {something} = this.state;
    return (
      <div>{something}</div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

class SearchBar extends React.Component<SearchBarProps, SearchBarState> {SearchBarPropsSearchBarState分别表示组件的预期道具类型和状态类型SearchBar。使用打字稿时必须提供 propTypes 和 stateType。
您可以通过使用关键字来避免提供类型,any但如果您真的想利用打字稿的优势,我强烈建议您不要走这条“邪恶”的道路。在您的情况下,您似乎没有指定状态类型并使用它,修复它将解决此问题。

编辑 1
在 interface 中SearchBarPropsoptionalArgument由于我们?在它前面添加了一个问号,因此成为一个可选参数,因此<SearchBar term='some term' />即使您不optionalArgument显式传递也不会显示任何错误。
希望这能解决您的问题!


Voč*_*čko 15

您只需要正确声明组件类型以包含 props 类型:

interface IMyProps {
    myValue: boolean,
}

const MyComponent: React.FC<IMyProps> = (props: IMyProps) => {
    ...
}

export default MyComponent;
Run Code Online (Sandbox Code Playgroud)

然后您可以将其用作:

import MyComponent from '../MyComponent';

...

return <MyComponent myValue={true} />
Run Code Online (Sandbox Code Playgroud)

瞧,打字稿很高兴。关于它的好处是打字稿现在只检查传递它们实际存在于 props 接口中的参数(可以防止拼写错误等)。

对于标准组件,它类似于(Swapnill 的示例中已有的内容):

class MyComponent extends React.Component<IMyProps, IMyState>{
    constructor(props: IMyProps){}
}
export default MyComponent;
Run Code Online (Sandbox Code Playgroud)


Qui*_*inn 8

已安装<YourComponent product={product} />使用<YourComponent {...product} />


sau*_*ito 6

我对此并不感到自豪,但是考虑到该线程中的其他解决方案,这似乎足够公平。

@react-native-community/slider此示例显示了具有一些默认属性但能够从外部接收(并覆盖)的自定义版本:

function CustomSlider(props: SliderProps) {
  return (
    <Slider
      style={{ width: '100%', height: 40, marginTop: 12 }}
      minimumValue={0}
      minimumTrackTintColor="#000000"
      maximumTrackTintColor="#000000"
      {...(props as any)}
    />
  );
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*son 5

刚刚有同样的问题。

您在 App 类的 Prop 接口上定义了名为 term 的成员,但在创建 App 元素时没有提供值。

请尝试以下操作:

ReactDOM.render(<App term="Foo" />, document.getElementById('root') as HTMLElement);
Run Code Online (Sandbox Code Playgroud)


Nou*_*non 5

对于函数式组件,此语法无需使用 React.FC 样板即可解决此错误:

interface FooProps {
  foo: FooType
}

function FooComponent({ foo }: FooProps): ReactElement {
  ...
}
Run Code Online (Sandbox Code Playgroud)