类型

时间:2018-02-26 16:22:01

标签: angular typescript ngrx

我正在使用TypeScript 2.7.1和ngrx。我的动作看起来像这样:

import { Action } from '@ngrx/store';


export const HEALTH_FORM_CONTENT_CHANGED = '[setupHealthForm] Content Changed';
export const HEALTH_FORM_TITLE_CHANGED = '[setupHealthForm] Title Changed';


export class SetupHealthFormContentChangedAction implements Action {
    public type: string = HEALTH_FORM_CONTENT_CHANGED;
    constructor(public payload: { content: string }) { }
}

export class SetupHealthFormTitleChangedAction implements Action {
    public type: string = HEALTH_FORM_TITLE_CHANGED;
    constructor(public payload: { title: string }) { }
}
export type Actions
    =
    SetupHealthFormContentChangedAction
    | SetupHealthFormTitleChangedAction;

我的Reducer看起来像这样:

import { Actions, HEALTH_FORM_TITLE_CHANGED, HEALTH_FORM_CONTENT_CHANGED } from './setup-health-form.actions';


export interface State {
    title: string;
    body: string;
}

const initialState: State = {
    title: '',
    body: ''
}

export function reducer(state: State = initialState, action: Actions): State {

    switch (action.type) {
        case HEALTH_FORM_TITLE_CHANGED: { 
            return {
                ...state,
                ...{ title: action.payload.title }
            }
        }
        case HEALTH_FORM_CONTENT_CHANGED: {
            return {
                ...state,
                ...{ body: action.payload.content }
            }
        }
        default: {
            return state;
        }
    }
}

export const body = (state: State) => state.body;
export const title = (state: State) => state.title;

但是我收到以下打字稿错误:

error TS2339: Property 'title' does not exist on type '{ content: string; } | { title: string; }'.
error TS2339: Property 'content' does not exist on type '{ content: string; } | { title: string; }'.

我发现解决此问题的唯一方法是导出具有任何类型的有效负载的操作。如何正确解决此问题以保留我的打字?

0 个答案:

没有答案