π Search Terms
mapped type, narrow, optional, undefined, union
π Version & Regression Information
This changed between versions 5.4 and 5.5. This can be reproduced in the playground.
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.5.2#code/C4TwDgpgBAkgdhAHgQwMbAPJmASwPZzIA2AzgDwCCAfFALxQDeAUFFANoDSUOcUA1hBB4AZlApRkJKAFc4AEwjCeEOVCTAI8qRU4BdKAH4oXAFxQEANwgAnXQbOyFShKvWa52vS1aGxeqAA+MvKKynLerGY6HLoA3EwAvlAAZIzenNy8AkKi4pLBTmFqiBpafjG+ljZQZjFRevEJ8UygkLC89Myswnh49lAkwNY8AObxrABGyNZmcNIAthM241BTAF4OIc4qjUxMAPT7UACiiJDoKmYMUD19ZoPDcCOBBaEusavTswtL1h-r-Ucbx2UASLXA0Aw0mAdHaSDQmGw+EIpDI8CoTCAA
π» Code
type InexactOptionals<A> = {
[K in keyof A as undefined extends A[K] ? K : never]?: undefined extends A[K]
? A[K] | undefined
: A[K];
} & {
[K in keyof A as undefined extends A[K] ? never : K]: A[K];
};
type In = {
foo?: string;
bar: number;
baz: undefined;
}
// Expected: { foo?: string | undefined; bar: number; baz?: undefined; }
type Out = InexactOptionals<In>
π Actual behavior
The A[K] | undefined in the mapped type ternary is narrowed to A[K], meaning that foo in the example is foo?: string.
π Expected behavior
The A[K] | undefined in the mapped type ternary is not narrowed, so we see foo?: string | undefined as expected.
Additional information about the issue
My use case is cheaply migrating a codebase to support exactOptionalPropertyTypes. It can also be useful for better React DX.
π Search Terms
mapped type, narrow, optional, undefined, union
π Version & Regression Information
This changed between versions 5.4 and 5.5. This can be reproduced in the playground.
β― Playground Link
https://www.typescriptlang.org/play/?ts=5.5.2#code/C4TwDgpgBAkgdhAHgQwMbAPJmASwPZzIA2AzgDwCCAfFALxQDeAUFFANoDSUOcUA1hBB4AZlApRkJKAFc4AEwjCeEOVCTAI8qRU4BdKAH4oXAFxQEANwgAnXQbOyFShKvWa52vS1aGxeqAA+MvKKynLerGY6HLoA3EwAvlAAZIzenNy8AkKi4pLBTmFqiBpafjG+ljZQZjFRevEJ8UygkLC89Myswnh49lAkwNY8AObxrABGyNZmcNIAthM241BTAF4OIc4qjUxMAPT7UACiiJDoKmYMUD19ZoPDcCOBBaEusavTswtL1h-r-Ucbx2UASLXA0Aw0mAdHaSDQmGw+EIpDI8CoTCAA
π» Code
π Actual behavior
The
A[K] | undefinedin the mapped type ternary is narrowed toA[K], meaning thatfooin the example isfoo?: string.π Expected behavior
The
A[K] | undefinedin the mapped type ternary is not narrowed, so we seefoo?: string | undefinedas expected.Additional information about the issue
My use case is cheaply migrating a codebase to support
exactOptionalPropertyTypes. It can also be useful for better React DX.