[英]Typescript: How do I define an interface for an object type's key value pair
I have an object called externalObject
that has various key:value pairs.我有一个名为
externalObject
的对象,它具有各种键:值对。
I also have a typescript interface that is defined as the following:我还有一个 typescript 接口,定义如下:
interface TestObject{
externalObject?: {}
}
My question is how do I further set the type for the externalObject's key as string and the values that are passed inside externalObject as string or number?我的问题是如何进一步将 externalObject 的键的类型设置为字符串,并将在 externalObject 内部传递的值设置为字符串或数字?
Note: we do not always know the key:value pairs.注意:我们并不总是知道键值对。 They vary each time.
他们每次都不同。
You can set any number of key/types on an interface in a similar way to assigning an object.您可以以类似于分配对象的方式在界面上设置任意数量的键/类型。 If you don't know the property names ahead of time, you can use a dynamic key:
如果您事先不知道属性名称,则可以使用动态键:
export interface ITestObject {
externalObject: {
[key: string]: string | number;
};
}
Alternatively, you can set the property as unknown
and cast it to the proper type.或者,您可以将该属性设置为
unknown
并将其转换为正确的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.