Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does TypeScript think my number|undefined Record<> property is undefined within a falsy check?

I don’t get why this code raises TS2532: Object is possibly 'undefined'. Why obj[prop] check is not enough and what is the proper way of writing this logic?

function test<T extends string>(obj: Record<T, number | undefined>, prop: T) {
  if (obj[prop]) obj[prop]--;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Typescript can’t handle the generics that well which is described in ms/TS#33014. Example:

function f<T extends 'a' | 'b'>(x: T) {
  if (x === 'a') {
    x; //  T extends "a" | "b"
  }
}

The easiest solution would be to store obj[prop] in a separate variable and if that value exists then assign a new value to obj[prop]:

function test<T extends string>(obj: Record<T, number | undefined>, prop: T) {
  let value = obj[prop];

  if (value) {
    obj[prop] = value - 1;
  }
}

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading