Encountering an issue with TypeScript's strictNullChecks
setting. There is a function handleAction
that requires an argument of type MyType
.
type MyType = {
prop: MyEnum;
// ... other properties
};
enum MyEnum {
Value1,
Value2,
// ... other values
}
async function handleAction(item: MyType) {
// Implementation logic here
}
There is an object myRecord
with a property nestedItem
that can potentially be null
.
type MyRecord = {
nestedItem: MyType | null;
// ... other properties
};
const myRecord: MyRecord = {
nestedItem: null, // or some MyType object
// ... other properties
};
The goal is to verify if nestedItem
exists and its prop
is Value1
. Two approaches were attempted:
Approach 1:
const isCertainCondition =
myRecord.nestedItem &&
myRecord.nestedItem.prop === MyEnum.Value1;
if (isCertainCondition) {
await handleAction(myRecord.nestedItem); // Error occurs here
}
Approach 2:
if (
myRecord.nestedItem &&
myRecord.nestedItem.prop === MyEnum.Value1
) {
await handleAction(myRecord.nestedItem); // No error with this approach
}
The first approach results in a TypeScript error:
Argument of type 'MyType | null' is not assignable to parameter of type 'MyType'.
Type 'null' is not assignable to type 'MyType'
The second approach executes without any error. What causes TypeScript to behave differently in these two approaches?