TypeScript is a language that exists only during the compilation process; at runtime, it is all converted into plain JavaScript.
When (de)serialization occurs at runtime, the data is deserialized into a JavaScript object. However, if you are asking if it's possible to create a TypeScript type definition for this incoming object, then the answer is yes.
It's important to note that the property names in TypeScript are not numbers but strings that may contain numeric values. This differentiation matters when creating type definitions because a string and a number are considered different types.
The first step is to define the Response objects:
interface IResponse {
description: string;
}
There are two approaches for defining the Responses object. The first approach can be used when the property names are known beforehand, while the second approach is more generic and supports any property names of a given type.
Known Names
interface IKnownResponses {
"200": IResponse;
"300"?: IResponse;
"400": IResponse;
}
This interface requires properties named "200" and "400", with the option to have a property named "300".
The "300" property is optional as indicated by the ? symbol in its definition.
Dynamic Names
interface IDynamicResponses {
[responseCode: string]: IResponse;
}
This interface allows any string to be used as a key/property name, with each property containing an IResponse
.
It is essentially an indexer definition.
Example
You can see these approaches in action with the following code snippet:
interface IResponse {
description: string;
}
interface IKnownResponses {
"200": IResponse;
"300"?: IResponse;
"400": IResponse;
}
interface IDynamicResponses {
[responseCode: string]: IResponse;
}
let knownResponses: IKnownResponses = {
"200": {
description: "foo"
},
"400": {
description: "bar"
}
};
let dynamicResponses: IDynamicResponses = {
"200": {
description: "foo"
},
"400": {
description: "bar"
},
"401": {
description: "baz"
}
};
console.log(staticResponses["200"].description);
console.log(knownResponses["401"].description);
https://jsfiddle.net/L8dpomL8/3/
While JSFiddle might not provide the best TypeScript IDE environment, you can copy this code to your preferred IDE to experiment and explore how typings can assist or fall short in your specific scenario.