[英]Get type of generic's value by key declared on a property in Typescript interface and use it as the type of a function's parameter
[英]Get type of an interface's property in TypeScript
我想通過它的屬性名稱從我的接口中提取一個類型以在記錄中重用。 我在按屬性名稱檢索類型的語法方面遇到困難。 我試圖讓它更具前瞻性,以便每當 id 類型更改為 number 時,例如我不必找到該記錄並將其更改為 number 。
interface Account {
name: string;
id: string;
createdOn: number;
}
然后在我的代碼中,我設置了一個useState
類型,它是我的界面中的id
(字符串)映射和當前帳戶是否正在加載的布爾值。
const [loadingAccounts, setLoadingAccounts] = useState<Record<string, boolean>>({});
我用什么替換string
以獲得id
的類型?
您可以使用[]
從接口中提取類型,如下所示:
interface Account {
name: string;
id: string;
createdOn: number;
}
let testVar: Account['id'];
如果您將在此代碼中看到, testVar 的類型將為字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.