Я пытаюсь войти в Typescript в сочетании с React и Redux.
Но сейчас я борюсь.
У меня такая ошибка:
./src/containers/Hello.tsx [tsl] ERROR in /home/marc/Development/TypeScript-React-Starter-master/src/containers/Hello.tsx(20,61) TS2345: Argument of type 'typeof Hello' is not assignable to parameter of type 'Component<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }>'. Type 'typeof Hello' is not assignable to type 'ComponentClass<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }>'. Type 'Hello' is not assignable to type 'Component<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }, ComponentState>'. Types of property 'setState' are incompatible. Type '{ (f: (prevState: {}, props: Props) => Pick<{}, K>, callback?: (() => any) | undefined): void; (state: Pick<{}, K>, callback?: (() => any) | undefined): void; }' is not assignable to type '{ (f: (prevState: ComponentState, props: { enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }) => Pick, callback?: (() => any) | undefined): void; (state: Pick<...>, callback?: (() => any)...'. Types of parameters 'f' and 'f' are incompatible. Types of parameters 'props' and 'props' are incompatible. Type 'Props' is not assignable to type '{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }'. Type 'Props' is not assignable to type '{ onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }'. Types of property 'onIncrement' are incompatible. Type '(() => void) | undefined' is not assignable to type '() => IncrementEnthusiasm'. Type 'undefined' is not assignable to type '() => IncrementEnthusiasm'.
Это мой компонент React:
import * as React from 'react';
import './Hello.css';
export interface Props {
name: string;
enthusiasmLevel: number;
onIncrement?: () => void;
onDecrement?: () => void;
}
class Hello extends React.Component<Props, {}> {
render(){
const { enthusiasmLevel, onIncrement, onDecrement } = this.props;
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic. :D');
}
return (
<div className = "hello">
<div className = "greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
<div>
<button onClick = {onDecrement}>-</button>
<button onClick = {onIncrement}>+</button>
</div>
</div>
);
}
}
export default Hello;
// helpers
function getExclamationMarks(numChars: number) {
return Array(numChars + 1).join('!');
}
Это файл, в котором возникает ошибка:
import Hello from '../components/Hello';
import * as actions from '../actions/';
import { StoreState } from '../types/index';
import { connect, Dispatch } from 'react-redux';
export function mapStateToProps({ enthusiasmLevel, languageName }: StoreState) {
return {
enthusiasmLevel,
name: languageName,
};
}
export function mapDispatchToProps(dispatch: Dispatch<actions.EnthusiasmAction>) {
return {
onIncrement: () => dispatch(actions.incrementEnthusiasm()),
onDecrement: () => dispatch(actions.decrementEnthusiasm()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Hello);
StoreState Интерфейс:
export interface StoreState {
languageName: string;
enthusiasmLevel: number;
}
Я не уверен, что в этом плохого. Единственный обходной путь, который сработал:
export default connect(mapStateToProps, mapDispatchToProps)(Hello as any);
что является уродливым решением в моих глазах.
@Frank Я добавил это.
Я работаю на себя. Похоже, проблема не в компоненте. (P.S. Также измените Component <Props, {}> на Component <Props>)



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Подсказки типа вашего интерфейса Props не совсем соответствуют интерфейсу, ожидаемому connect()(), как указано в сообщении об ошибке:
Type 'Hello' is not assignable to type 'Component<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; }, ComponentState>'.
onIncrement и onDecrement не должны быть дополнительными иonIncrement и onDecrement возвращают не void, а IncrementEnthusiam и DecrementEnthusiam соответственно.Ваш интерфейс Props должен выглядеть так:
export interface Props {
name: string;
enthusiasmLevel: number;
onIncrement: () => IncrementEnthusiasm;
onDecrement: () => DecrementEnthusiasm;
}
Можете ли вы опубликовать свой интерфейс StoreState?