I have an object called externalObject
that has various key:value pairs.
I also have a typescript interface that is defined as the following:
JavaScript
x
4
1
interface TestObject{
2
externalObject?: {}
3
}
4
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?
Note: we do not always know the key:value pairs. They vary each time.
Advertisement
Answer
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:
JavaScript
1
6
1
export interface ITestObject {
2
externalObject: {
3
[key: string]: string | number;
4
};
5
}
6
Alternatively, you can set the property as unknown
and cast it to the proper type.