Typescript: Required<T> does not remove '| undefined' from properties of T (strictNullChecks=true)

356 Views Asked by At

Because of the following sentence in the typescript doc I thought that Required<T> will also remove | undefined from all properties of Type T as long as strictNullChecks are activated.

Note that in strictNullChecks mode, when a homomorphic mapped type removes a ? modifier from a property in the underlying type it also removes undefined from the type of that property:

I also find stackoverflow Posts that have problems because of the removed undefined.

Unfortunately I don't see this behavior.

The problem

? is removed but | undefined is not.

Example:

interface Entity1 {
    optionalVal?: string | undefined;
}
type CompleteEntity1 = Required<Entity1>

VSC tells me on mouseover

type CompleteEntity1 = {
    optionalVal: string | undefined;
}

So

const testCompleteEntity1: CompleteEntity1 = {
    optionalVal: undefined  // <== No Error
}

I already found a solution that works for me.

type RequiredAndDefined<T> = {
    [P in keyof T]-?: Exclude<T[P], null | undefined>
}

interface Entity2 {
    optionalVal?: string | undefined | null;
}
type CompleteEntity2 = RequiredAndDefined<Entity2>

const testEntity2: Entity2 = {
    optionalVal: undefined  // <== No error as expected
}

const testCompleteEntity2: CompleteEntity2 = {
    optionalVal: undefined  // <== Error as expected
}

...but I don't understand why I need this (I guess Required should be enough to detect undefined ?!)

My current tsconfig.json

{
  "extends": "@tsconfig/node16-strictest/tsconfig.json",
  "compilerOptions": {

    "outDir": "./dist/",

    "lib": ["es2022"],

    "noPropertyAccessFromIndexSignature": false,

    "resolveJsonModule": true,
    "strictNullChecks": true                           /* test...to let Required<T> remove '| undefined' from the types of the properties of T (https://stackoverflow.com/q/57324324/7869582) */
  }
}
0

There are 0 best solutions below