簡體   English   中英

如何在 Typescript 中鍵入以下對象/類型

[英]How to type following object/type in Typescript

我有以下內容:

一個用戶類型,它是:

export type User = {
  id: string | null;
  email: string | null;
  firstName: string | null;
  lastName: string | null;
  verified: boolean | null;
};

以及以下 state:

let initialState: UserSliceState = {
  user: {
    id: null,
    firstName: null,
    lastName: null,
    email: null,
    verified: null,
  },
  error: null,
  isLoading: false,
};

我想輸入它,但我不知道該怎么做,我試過這個:

type UserSliceState = {
  user: {
    [field: keyof User]: User;
  };
  error: string | null;
  isLoading: boolean;
};

但它在[field: keyof User]上給了我一個錯誤,我不知道我所做的是否有效:它說An index signature parameter can't be a union type, consider using a mapped object instead

有什么想法嗎? 謝謝

您只需要將您的用戶類型添加到UserSliceState

type UserSliceState = {
  user: User;
  error: string | null;
  isLoading: boolean;
};

暫無
暫無

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

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