Occasionally, TypeScript struggles to infer the return type of a lambda or method, prompting me to manually specify it for enhanced type safety.
This issue arises when dealing with promises or more complex callbacks (such as those used in the parsimmon
parsing library).
I have yet to discover a method of specifying the return variable's type without resorting to creating a local variable:
interface ITest {
x: number;
y: string;
}
// This passes type checking, but I'd prefer it didn't
function f1() {
return {x:5} as ITest;
}
// This also type checks, though not ideal
// (I understand it's a cast, but included to demonstrate its ineffectiveness)
function f2() {
return <ITest>{x:5};
}
// Correctly fails to type-check
function f3() {
const x: ITest = {x:5};
return x;
}
Is there an alternative approach to achieving type checks without necessitating the creation of a local variable? I acknowledge that I could simply type function f4(): ITest
, but my scenarios tend to be more complex:
return P.string(" for ")
.then(P.takeWhile(c => c !== ' ').skip(P.string(" in ")))
.chain(value => P.takeWhile(c => c !== ' ')
.chain(array => parseNgOptionsTrackBy().atMost(1)
.map(trackBy => {
// Solely created variable for type-checking
const r: NgOptionsData = {
select: expressions.select,
label: expressions.label,
value: value,
array: array,
trackexpr: trackBy ? trackBy[0] : undefined
};
return r;
})));
or:
return new Promise((resolve, reject) => {
// Some code executed, then variable solely for type-checking
const result: ViewInfo = {
fileName: fileName,
ngModuleName: ngModuleName,
controllerName: controllerName,
controllerViewInfos: viewInfos};
resolve(result);
});
In essence, when deeply embedded within a lambda, defining a return type is not always straightforward.
UPDATE There seems to be doubt surrounding TypeScript's ability to infer resolve
for promises. Fortunately, my app is open-source. I have made a commit illustrating the issue on a specific branch:
https://github.com/emmanueltouzery/ng-typeview/tree/so_question
Please review the latest commit on that branch. Even after removing a field from the structure being filled (intentionally seeking a build error), the project compiles without issues. And yes, I did indicate the expected return type of the function,
Promise<ControllerScopeInfo>
.
This poses a type-safety concern.
Should you wish to compile, execute npm install
followed by tsc
. Though presumably, inspecting the source and the tsconfig may suffice for you to trust my assertion regarding the compilation status.