![](/img/trans.png)
[英]How to type enum and object to have same properties React Typescript
[英]Typescript type of object literals of enum?
如何为下面的 object 定义类型或接口?
这里 USER_TYPE 是一个枚举
type User = {
[key in USER_TYPE]: { state: any };
};
用户 object
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"
}
错误指示返回
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 };
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.