我有一個這樣的 JSON:
{ users: {
"username": {"name": "text","last_name": "other text"},
"username2": {"name": "text","last_name": "other text"},
"username3": {"name": "text","last_name": "other text"}
...
}
我想將其輸入為通用型別,如下所示:
type UserInfo = {name:string, last_name:string}
type user<T> = {
T: UserInfo
}
type users = {
users: user<string>
}
我正在嘗試使用用戶的泛型作為物件的鍵,因此我不必為用戶名、用戶名2 等定義鍵并使其可擴展為“n”用戶名。但它不作業
uj5u.com熱心網友回復:
您的方法中的錯誤是
type UserInfo = {name:string, last_name:string}
type user<T> = {
// you cannot use type T as a key which needs to be a value
//(that value can be either string or number as key)
T: UserInfo //this is incorrect
}
type users = {
users: user<string>
}
提到這一點,您可以使用內置的“記錄”型別來實作您的目標。
type UserInfo = {
name: string;
last_name: string;
};
type Users = Record<string, UserInfo>;
// this will suffice, if you want the key to be just string and need not follow any pattern like if its just username or username1.
const users: Users = {
username: { name: "asdsa", last_name: "asdsa" },
anyNameOfTheUser: { name: "asdsa", last_name: "asdsadd" },
};
uj5u.com熱心網友回復:
我想簡單的方法將輸入為記錄,如:
type UserInfo = {name:string, last_name:string}
type users = {
Record<string,UserInfo>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510462.html
標籤:json打字稿仿制药
