json - '{}' türü 'IntrinsicAttributes & IntrinsicClassAttributes' türüne atanamaz
Şu anda basit bir React uygulaması yapıyorum. Bu benim 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();
ve işte burada benim app.tsx dosyam var
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;
ve ayrıca arama çubuğu konteynerim:
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;
ve sonunda benim tsconfig.json dosyam var:
{
"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"
]
}
Hata üstüne hata alıyorum ve bir hatayı düzelttiğimde başka bir hata ortaya çıkıyor, bunu böyle davranmaya neyin neden olduğunu bilmiyorum. İşte son hata:
./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 '{}'.
tsconfig.json dosyamı değiştirerek düzeltmeye çalıştım ama aynı hata hâlâ görünüyor, yanlış yaptığım ne ve neden TypeScript böyle davranıyor. Bu konuda çok yeniyim ve bu örnekle React'in tamamen nasıl çalıştığını anlamaya çalışıyorum.
Cevap #1
Tümüyle bileşene aktarılan bir nesneyi beyan ederek, "IntrinsicAttributes & IntrinsicClassAttributes türüne atanamaz" türündeki pek çok hatayı (Microsoft tarafından kapatılan sorun) çözdüm.
OP'nin örneğinde, çalışması için term={this.props.term} kullanmak yerine {...searchBarProps} kullanın:
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>
);
}
Cevap #2
Tek yapmanız gereken, özellikler tipini dahil etmek için bileşen tipini doğru şekilde beyan etmektir:
interface IMyProps {
myValue: boolean,
}
const MyComponent: React.FC<IMyProps> = (props: IMyProps) => {
...
}
export default MyComponent;
Sonra bunu şöyle kullanabilirsiniz:
import MyComponent from '../MyComponent';
...
return <MyComponent myValue={true} />
Ve işte, TypeScript mutlu. Bunun güzel yanı, TypeScript'in artık sadece props arayüzünde gerçekten var olan parametrelerin geçilip geçilmediğini kontrol etmesi (yazım hatalarını ve benzerlerini önleyebilir).
Standart bileşen için, Swapnill'in örneğinde zaten olan şeye benzer bir şey olurdu:
class MyComponent extends React.Component<IMyProps, IMyState>{
constructor(props: IMyProps){}
}
export default MyComponent;
Cevap #3
Buradaki sorun tslint ayarlarınızla ilgili değil. Aşağıdaki kod parçasına bakın:
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>
)
}
}
class SearchBar extends React.Component<SearchBarProps, SearchBarState> { içinde, SearchBarProps ve SearchBarState, sırasıyla SearchBar bileşeninin beklenen prop türünü ve durum (state) türünü belirtir. Typescript kullanırken propTypes ve stateType vermeniz gerekir.
any anahtar kelimesini kullanarak tür vermekten kaçınabilirsiniz, ancak Typescript'ten tam anlamıyla faydalanmak istiyorsanız bu "kötü" yolu izlemenizi kesinlikle önermem. Sizin durumunuzda ise state türünü belirtmediğiniz ve kullandığınız görülüyor, bu sorunu düzeltmek problemi çözecektir.
Düzenleme 1
SearchBarProps arayüzünde, optionalArgument önüne bir soru işareti ? eklediğimizde isteğe bağlı bir argüman haline gelir, bu nedenle <SearchBar term='some term' /> kodunu optionalArgument'ı açıkça geçirmeseniz bile hiçbir hata göstermeyecektir.
Umarım bu sorununuzu çözer!
