使用接口的打字稿中的问题

时间:2020-10-05 18:53:40

标签: javascript typescript

我是使用打字稿创建的:

import React, {FC} from 'react';
interface Interface {
    name:string,
    age:number
}
const Home: React.FC<Interface> = (info) => {
    return (
        <div>
            <h1>{info.name}</h1>
        </div>
    );
};

export default Home;

///

const info = {name:'Boris', age:45}

function App() {
  return (
    <div className="App">
      <Home info={info}/>
    </div>
  );
}

...但是我从打字稿中得到一个错误: Type '{ info: { name: string; age: number; }; }' is not assignable to type 'IntrinsicAttributes & Interface & { children?: ReactNode; }'.   Property 'info' does not exist on type 'IntrinsicAttributes & Interface & { children?: ReactNode; }'
问题:如何避免这种情况以及它为什么出现?

2 个答案:

答案 0 :(得分:2)

此代码在这里:

private var yourUptatedValue: String
private var settingVM : SettingsModel()

settingVM.yourPickerValue.bind { [unowned self] in // or [weak self]
    self.yourUpdatedValue = $0
    UserDefaults.standard.string($0, forKey: KeyValuePair.selectedStatus)
}

假设组件find . -type f -perm -u=r+x需要2个道具:interface Interface { name:string, age:number } const Home: React.FC<Interface> = //... Home

此代码在这里:

name

传入一个名为age的道具。


所以您要么要传递<Home info={info}/> info作为道具:

name

或者您要声明age道具:

<Home name={info.name} age={info.age}/>

(请注意info的解构分配,该分配将interface Props { info: { name:string, age:number, } } const Home: React.FC<Props> = ({ info }) => { /* ... */ } // Pass props like: <Home info={info}/> 属性分配给局部变量({ info })。)

Playgorund

答案 1 :(得分:0)

您应该在Home组件中破坏道具。

应该是

const Home: React.FC<Interface> = ({ info }) => {
  return (
    <div>
      <h1>{info.name}</h1>
    </div>
  );
};