![](/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.