枚举的对象文字的打字稿类型?

Typescript type of object literals of enum?

如何为以下对象定义类型或接口?

这里USER_TYPE是枚举

type User = {
  [key in USER_TYPE]: { state: any };
};

用户对象

  const user: User = {
    [USER_TYPE.EMPLOYEE]: {state: { userPhoneNum: userPhoneNum } },
    [USER_TYPE.ADMIN]: {  state: { userData: userData } }
  };

return user[userType] // userType is same as enum defined

用户类型枚举

export enum USER_TYPE {
  EMPLOYEE = "EMPLOYEE",
  ADMIN = "ADMIN"
}

error表示在return

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User'.
  No index signature with a parameter of type 'string' was found on type 'User'.ts(7053)

解决方案

这对我有用。

type User = {
  [key in string]: { state: any };
};