Skip to content

Commit 49ec0b0

Browse files
Strip null and undefined from targets when relating from certain atomic types.
1 parent cb6325d commit 49ec0b0

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/compiler/checker.ts

+17-1
Original file line numberDiff line numberDiff line change
@@ -10631,6 +10631,22 @@ namespace ts {
1063110631
target = getSimplifiedType(target);
1063210632
}
1063310633

10634+
// Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
10635+
// If so, reporting the `null` and `undefined` in the type is hardly useful.
10636+
// First, see if we're even relating an atomic type to a union.
10637+
// Then see if the target is stripped down to a single non-union type.
10638+
// We actually want to remove null and undefined naively here (rather than getNonNullableType),
10639+
// since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
10640+
// when dealing with generics.
10641+
if (target.flags & TypeFlags.Union &&
10642+
source.flags & ((TypeFlags.Primitive | TypeFlags.Object) & ~(TypeFlags.Nullable | TypeFlags.Void)) &&
10643+
(target as UnionType).types.length <= 3 && maybeTypeOfKind(target, TypeFlags.Nullable)) {
10644+
const nullStrippedTarget = extractTypesOfKind(target, ~TypeFlags.Nullable);
10645+
if (!(nullStrippedTarget.flags & (TypeFlags.Union | TypeFlags.Never))) {
10646+
target = nullStrippedTarget
10647+
}
10648+
}
10649+
1063410650
// both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
1063510651
if (source === target) return Ternary.True;
1063610652

@@ -12223,7 +12239,7 @@ namespace ts {
1222312239
if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
1222412240
return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
1222512241
}
12226-
return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); // Type alias unavailable, fall back to non-higherorder behavior
12242+
return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); // Type alias unavailable, fall back to non-higher-order behavior
1222712243
}
1222812244

1222912245
function getNonNullableType(type: Type): Type {

0 commit comments

Comments
 (0)