I’m running into a problem that TypeScript should solve for me, but it doesn’t. I have a value which is sometimes an array and sometimes null/undefined. I want to call forEach on this value, but I need to make sure that every time I call it, I’m using optional chaining to prevent errors. But TypeScript isn’t warning me when I leave out the optional chaining. I’ve tried many different ways of declaring this type, none of which have worked. I have a 10,000 line file that I’m trying to make run smoothly, and don’t want to have to keep hand-combing through to catch these problems.
maybeArray.forEach(...) -> maybeArray?.forEach(...)
Is there any way to get TypeScript to warn me when I leave off the optional chaining?
I’m using TypeScript 5.3.3 with Node.js in Visual Studio Code.
Here’s the simplest version:
const maybeArray: number[] | undefined = undefined;
maybeArray.forEach(val=>val++); // no TypeScript warning, but there should be.
// note that on the above line, mousing over maybeArray shows "const maybeArray: number[]".
I’ve also tried
type MaybeArray = number[] | undefined;
const maybeArray: MaybeArray = undefined;
maybeArray.forEach(val=>val++); // no TypeScript warning, but there should be.
And I’ve also tried
type MaybeArray = number[] | undefined;
const maybeArray = undefined;
(maybeArray as MaybeArray).forEach(val=>val++); // no TypeScript warning, but there should be.
And even
type MyObject = {
maybeArray?: number[],
};
const myObject:MyObject = {};
(myObject.maybeArray).forEach(val=>val++); // no TypeScript warning, but there should be.
I thought I could get a useful result by using false instead of undefined, but false doesn’t work with optional chaining.
type MaybeArray = number[] | false;
const maybeArray = false;
(maybeArray as MaybeArray)?.forEach(val=>val++); // correct TypeScript warning because optional chaining doesn't work on FALSE.
tscongif:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"target": "es6",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"typeRoots": ["./src/types","./node_modules/@types"],
"strictNullChecks": false,
"strict": false,
"noEmitOnError": false,
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
