typescript - 儘管已將 null 設為選項,仍無法將 React useFormState 的類型屬性設為 null
我正在使用 Typescript。我有一個 type,其中有一個屬性 'message',它可以是字串或 null
export type State = {
message: string | null;
};
不過,當我嘗試將該屬性設為 null 時,我收到以下類型錯誤。它只允許我將其設為字串。
Types of property 'message' are incompatible.
Type 'null' is not assignable to type 'string'.
我正在使用這種類型,如下所示:
const initialState = { message: null };
const [state, dispatch] = useFormState(postFiles, initialState);
export async function postFiles(prevState: State, formData: FormData) {
console.log(formData);
return {
message: "Uploaded",
};
}
我已經嘗試將 strictNullChecks 設為 true,但我仍然收到錯誤。這可能是什麼原因?我是不是漏掉了什麼?
答案#1
問題是因為 useFormState 的類型如下:
function useFormState<State, Payload>(
action: (state: Awaited<State>, payload: Payload) => State | Promise<State>,
initialState: Awaited<State>,
permalink?: string,
): [state: Awaited<State>, dispatch: (payload: Payload) => void];
由於 action 被定義為 (state: Awaited<State>, payload: Payload) => State,這意味著該 action 的返回值,在這個例子中是 postFiles,將會自動被 推斷 為 State。
那個回傳值是一個物件字面量,其中 message 是一個字串。這意味著 initialState: Awaited<State> 會被推斷為一種類型,其中 message 是 string(因為它是從該回傳值推斷出來的),所以你傳給初始值物件中的 message 的 null 值,對這個自動推斷的類型來說是不合法的。
要修復,請明確傳遞類型參數,以便 TypeScript 提前知道此值可以是什麼。
const [state, dispatch] = useFormState<State, FormData>(postFiles, initialState);
