[英]How to set typescript type for key value in objects?
I have an object of currency types with properties like this:我有一个具有如下属性的货币类型对象:
CurrencyType = {
usd: {
country: 'United States',
symbol: '$USD',
icon: <USD />
},
cad: {
country: 'Canada',
symbol: '$CAD',
icon: <CAD />
},
etc...
}
How can I write the type so that it takes a dynamic value for the key of each object – usd
, or cad
如何编写类型以便它为每个对象的键获取动态值 - usd
或cad
I am trying to find how I can set the typescript type for for this object above so that the object names are included.我试图找到如何为上面的这个对象设置打字稿类型,以便包含对象名称。
Basically want something like this:基本上想要这样的东西:
export interface CurrencyTypes {
[currencyName: string]: {
country: string;
symbol: string;
icon: React.ReactNode;
}
I believe you're looking for something like this where you iterate over the values of another type.我相信您正在寻找这样的东西,您可以在其中迭代另一种类型的值。
type CountryCurrency = "usd" | "cad" | "aud";
export interface CurrencyTypes {
[Currency in CountryCurrency]: {
country: string;
symbol: string;
icon: React.ReactNode;
}
}
This will require that any object that implements the CurrencyTypes
interface has all of the keys that are possible values of CountryCurrency
这将要求任何实现CurrencyTypes
接口的对象都具有CountryCurrency
可能值的所有键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.