簡體   English   中英

基於枚舉值的可選屬性

[英]Optional property based on value of enum

我正在嘗試讓一些類型為 react useReducer

基本上我有一個動作,它有一個基於另一個屬性的值的可選屬性( data ) - 所以如果STATUSVIEWEDIT ,則該動作必須具有data屬性。 我幾乎有一些工作,但有一種情況(見下文)失敗。

我想這樣做的一種方法是顯式設置STATUS.NEW不需要額外的屬性( { type: 'SET_STATUS'; status: STATUS.NEW } ),但我想知道是否有更好的方法。 如果將來我添加了一堆不同的狀態,那么我必須指定每個狀態以不需要 data 屬性。

打字稿游樂場

enum STATUS {
    NEW = 'new',
    VIEW = 'view',
    EDIT = 'edit'
}

/*
    if status is 'view', or 'edit', action should also contain
    a field called 'data'
*/
type Action =
    | { type: 'SET_STATUS'; status: STATUS }
    | { type: 'SET_STATUS'; status: STATUS.VIEW | STATUS.EDIT; data: string; }


// example actions

// CORRECT - is valid action
const a1: Action = { type: 'SET_STATUS', status: STATUS.NEW }

// CORRECT - is a valid action
const a2: Action = { type: 'SET_STATUS', status: STATUS.VIEW, data: 'foo' }

// FAILS - should throw an error because `data` property should be required
const a3: Action = { type: 'SET_STATUS', status: STATUS.EDIT }

// CORRECT - should throw error because data is not required if status is new
const a4: Action = { type: 'SET_STATUS', status: STATUS.NEW, data: 'foo' }

問題的第二部分是我如何將其合並到下面的useCallback中。 我原以為 useCallback 能夠正確地將參數推斷為適當的操作類型。

/* 
    assume:
    const [state, dispatch] = useReducer(stateReducer, initialState)
*/

const setStatus = useCallback(
    (payload: Omit<Action, 'type'>) => dispatch({ type: 'SET_STATUS', ...payload }),
    [],
)

/* 
complains about:

Argument of type '{ status: STATUS.EDIT; data: string; }' is not assignable to parameter of type 'Pick<Action, "status">'.
  Object literal may only specify known properties, and 'data' does not exist in type 'Pick<Action, "status">'
*/
setStatus({ status: STATUS.EDIT, data: 'foo' })

您可以定義需要data的雕像聯合,然后在代表所有其他人的行動中排除它們:

enum STATUS {
    NEW = 'new',
    VIEW = 'view',
    EDIT = 'edit'
}

type WithDataStatuses = STATUS.VIEW | STATUS.EDIT;

type Action =
    | { type: 'SET_STATUS'; status: Exclude<STATUS, WithDataStatuses> }
    | {
        type: 'SET_STATUS';
        status: WithDataStatuses;
        data: string;
    }

// now CORRECT - data is required
const a3: Action = { type: 'SET_STATUS', status: STATUS.EDIT }

回答問題的第二部分:-)

假設您已按照@Aleksey L. 的建議定義了ActionsuseCallback可以按如下方式鍵入useCallback

// This is overloaded function which can take data or not depending of status
interface Callback {
  (payload: { status: Exclude<STATUS, WithDataStatuses> }): void;
  (payload: { status: WithDataStatuses; data: string; } ): void;
}

const [state, dispatch] = React.useReducer(stateReducer, {})
// Explicitly type useCallback with Callback interface
const setStatus = React.useCallback<Callback>(
  (payload) => dispatch({ type: 'SET_STATUS', ...payload }),
  [],
)
setStatus({ status: STATUS.EDIT, data: 'foo' })
setStatus({ status: STATUS.NEW })

工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM