Home > Mobile >  NonNullable does not work on Generic property
NonNullable does not work on Generic property

Time:04-21

I tried to create type which makes specific key is non nullable.

My IDE (WebStorm) says property is non-nullable when I try to access property, but when assigning the value to a constant, WebStorm says that the value is not non-nullable.

What is wrong with my code?

My code:

interface NullableA {
    a?: number;
}

export type EnsureKeyExists<T, K extends keyof T> = T & {
    [P in K]: NonNullable<T[P]>;
};

const a: EnsureKeyExists<NullableA, 'a'> = { a: 2 };

const nonNullNumber: number = a.a // => this is error

Property seems to be not nullable type

enter image description here

When assigning, value is nullable

enter image description here

This is my tsconfig.json file:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictFunctionTypes": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

Other info:

  • WebStorm version is 2021.3.2

CodePudding user response:

I solved it with -?:

export type EnsureKeyExists<T, K extends keyof T> = T & {
    [P in K]-?: T[P];
};

See this PR for further reference.

Using Required would also work:

export type EnsureKeyExists<T, K extends keyof T> = T & Required<{
    [P in K]: T[P];
}>;
  • Related