gpt4 book ai didi

angular - ngrx reducer 属性在类型上不存在

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:28 24 4
gpt4 key购买 nike

我正在使用 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;

但是我收到以下 typescript 错误:

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; }'.

我发现解决此问题的唯一方法是导出一个带有 any 类型负载的 Action 。如何正确解决此问题以保留我的打字?

最佳答案

要使用可区分的联合类型及其switch 类型保护行为,type 的类型必须是字符串文字类型(基本上只能是字符串类型单值)。你的 type 字段是 string 即使你给它分配了一个常量。发生这种情况是因为 typescript 假定您希望 ot 改变该字段,因此它将其键入为 string。如果您将其标记为 readonly 并删除显式 string 类型,则该字段将使用常量类型(字符串文字类型)和您的 switch 将正确键入检查:

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

export class SetupHealthFormTitleChangedAction implements Action {
public readonly type = HEALTH_FORM_TITLE_CHANGED
constructor(public payload: { title: string }) { }

Playground sample code

关于angular - ngrx reducer 属性在类型上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48992765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com