Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario:
function extractField(data: unknown): string {
if (typeof data !== 'object') {
throw new Error('e1');
}
if (data == null) {
throw new Error('e2');
}
const { field } = data;
if (typeof field !== 'string') {
throw new Error('e3');
}
return field;
}
My objective is to extract a string field from the data and ensure that the code throws an error if the data's structure is invalid. However, I am facing an issue with type checking. The code currently results in an error stating, "Property 'field' does not exist on type '{}'." I am aware that adding any
can resolve this issue, but I am determined to find a type-safe solution without relying on any
.