错误TS2345:类型'StateType'的参数不能分配给类型'{demo_state ?: {demo_state:{title:string; }; }; }'

时间:2020-03-23 00:47:59

标签: typescript

已修复:所以问题出在我的减速器demo_state.ts上,尤其是在state = initState上。我将其更改为state = initState.demo_state

import {initState} from '../initState';

const demo_state = (state = initState.demo_state, action) => {
    switch (action.type) {

        default:
            return state
    }
}

export default demo_state;

原始: 我是TypeScript的新手。我将TypeScript集成到React / Redux中,目前在TypeScript中有一个错误,我不知道如何解决。

我创建了文件名StateType.d.ts

interface DemoState {
  title: string
}

export interface StateType {
  demo_state: DemoState
}

还有文件initState.ts(此文件保存了我们应用的初始状态)

import {StateType} from './type/StateType';

export const initState: StateType = {
    demo_state: {
        title: "Hello World"
    }
}

最后,initState.ts文件被导入到client.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// API from redux createStore(<reducer>)
import { createStore, applyMiddleware } from 'redux';
// Component from react-redux help share store to all container components
import { Provider } from 'react-redux';
// Import the reducer function with arbitrary name
import rootReducer from './reducers';
// Import thunk
import thunk from 'redux-thunk';
// Import redux logger
import { createLogger } from 'redux-logger';
// Root State for App
import { initState } from './initState';

//const middlewares = [ thunk ];
const middlewares = [ thunk, createLogger() ]; 

const appStore = createStore(rootReducer, initState, applyMiddleware(...middlewares));

ReactDOM.render(
<Provider store={ appStore }>
    <App />
</Provider>, 
document.getElementById('app'));

我的类型脚本命令如下:

"scripts": {
    "type-check-client": "tsc -p ./src/client/tsconfig.json || true",
},

运行npm run type-check-client时,出现以下错误:

src/client/client.tsx(20,43): error TS2345: Argument of type 'StateType' is not assignable to parameter of type '{ demo_state?: { demo_state: { title: string; }; }; }'.
  Types of property 'demo_state' are incompatible.
    Property 'demo_state' is missing in type 'DemoState' but required in type '{ demo_state: { title: string; }; }'.

有人可以告诉我我在这里做错了什么吗?我将不胜感激。

PS :我将减速器放在这里

  • 第一个文件:demo_state.ts
import {initState} from '../initState';
import {StateType} from '../type/StateType';

const demo_state = (state = initState, action: any): StateType => {
    switch (action.type) {

        default:
            return state
    }
}

export default demo_state;
  • 第二个文件:index.ts
import { combineReducers } from 'redux';
import demo_state from './demo_state';

export default combineReducers({
    demo_state
    //another_state_prop,
})

0 个答案:

没有答案