[英]Get type of an interface's property in TypeScript
I want to extract a type from my an interface by it's property name to reuse in a Record.我想通过它的属性名称从我的接口中提取一个类型以在记录中重用。 I am having difficulties with syntax to retrieve the type by property name.
我在按属性名称检索类型的语法方面遇到困难。 I am trying to make it a bit more future-proof so that whenever id type changes to number for example I don't have to find that one record and change that to number too.
我试图让它更具前瞻性,以便每当 id 类型更改为 number 时,例如我不必找到该记录并将其更改为 number 。
interface Account {
name: string;
id: string;
createdOn: number;
}
Then in my code I am setting a useState
type which is a map of id
(string) from my interface and boolean whether account is currently loading.然后在我的代码中,我设置了一个
useState
类型,它是我的界面中的id
(字符串)映射和当前帐户是否正在加载的布尔值。
const [loadingAccounts, setLoadingAccounts] = useState<Record<string, boolean>>({});
What do I replace string
with to get the type of the id
?我用什么替换
string
以获得id
的类型?
You can extract a type from interface by using []
as follows:您可以使用
[]
从接口中提取类型,如下所示:
interface Account {
name: string;
id: string;
createdOn: number;
}
let testVar: Account['id'];
If you will see in this code, type of testVar will be string.如果您将在此代码中看到, testVar 的类型将为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.