如何为下面的对象定义类型或接口?
这里的 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
userType 枚举
export enum USER_TYPE {
EMPLOYEE = "EMPLOYEE",
ADMIN = "ADMIN"
}
error 表示返回
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)
答案 0 :(得分:0)
解决方案
这对我有用。
type User = {
[key in string]: { state: any };
};