[英]Define a Typescript type from properties of objects in a list
Say I have a list of objects like:假设我有一个对象列表,例如:
const TABS = [
{
name: 'Home',
// other properties
},
{
name: 'Profile',
// other properties
}
];
How can I define type Tab
, which is a type for the 'name' field of each object in the list?如何定义type Tab
,它是列表中每个对象的“名称”字段的类型? Basically the equivalent to基本上相当于
type Tab = 'Home' | 'Profile';
in the case above (but without the need to repeat "Home" and "Profile" in both definitions).在上述情况下(但无需在两个定义中重复“主页”和“个人资料”)。
This is possible as long as the value of TABS
is known at compile time and you prevent the compiler from widening its type to something like Array<{name: string}>
.只要TABS
的值在编译时是已知的,并且您阻止编译器将其类型扩展为Array<{name: string}>
类的内容,这就是可能的。 You want the compiler to remember the specific string literal types of the values you put into the name
properties, and not just treat them as string
s.您希望编译器记住您放入name
属性的值的特定字符串文字类型,而不仅仅是将它们视为string
。 The easiest way to do this is to use a const
assertion on the TABS
array literal at creation time:最简单的方法是在创建时对TABS
数组文字使用const
断言:
const TABS = [
{
name: 'Home',
},
{
name: 'Profile',
}
] as const; // <-- need this
Now the compiler knows that TABS
is a pair of objects and that the first one has a name
property of the string literal type "Home"
, and that the second one has a name
property of the string literal type "Profile"
.现在,编译器知道TABS
是一对对象和第一个有name
的字符串文字类型的财产"Home"
,而第二个有name
的字符串文字类型的财产"Profile"
。
At this point you can just use lookup types to get the name
property of the elements at the numeric ( number
) indices of the type of TABS
:此时,您可以仅使用查找类型来获取TABS
类型的数字( number
)索引处元素的name
属性:
type Tab = (typeof TABS)[number]["name"];
// type Tab = "Home" | "Profile"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.