Take into account the following code snippet:
type Example = {
prop1: string,
prop2: number
}
const values = ['x', 'y', 'z'];
const examples = values.map<Example>((val, i) => {
return {
prop1: val,
prop2: i
}
});
This will not strictly enforce the type of the return value from the map function. For instance, you could do this:
return {
prop1: val,
prop2: i,
extraProperty: 'test' // This is allowed! (undesired behavior)
}
This behaves similarly to using a generic type and applying a type assertion on the return value like this:
return {
prop1: val,
prop2: i,
extraProperty: 'test' // allowed (undesirable)
} as Example
The only method I have found to fully enforce the type is by creating an intermediary variable:
const resultValue: Example = {
prop1: val,
prop2: i,
// extraProperty: 'test' // Compiler error - TypeScript catching mistakes!
}
return resultValue;
Is there any syntax that enables creating an anonymous object in the return
statement while completely enforcing the type, instead of just using a type assertion?