Home > Enterprise >  typescript does not detect the type was narrowed
typescript does not detect the type was narrowed

Time:08-18

function encodeToken(value: number | string | null | undefined) {
  if (value !== null && value !== undefined) {
    value = value.toString()
  }

  return encodeBase64(value) // typescript complains this line
}

function encodeBase64(value: string | null | undefined) { ... }

Typescript complains as below:

(parameter) value: string | number Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'


The "value" which I passed to encodeBase64 would be string | null | undefined, any number value will transform to string,

Does anyone know how to fix it? Very appreciated

CodePudding user response:

This happens when "strictNullChecks" is false in tsconfig.

Without the 'if' statement, this is ok:

function encodeToken(value: number | string | null | undefined) {
  value = value.toString() //narrowed down from `number | string` to `string` after this line
  return encodeBase64(value) 
}

But this does not work:

function encodeToken(value: number | string | null | undefined) {
  if (value !== null && value !== undefined) {
    value = value.toString()
  }
  return encodeBase64(value) //value is still considered `number | string`, so it complains
}

Apparently, TS skipped some checking for the if (value !== null && value !== undefined) part when "strictNullChecks" is false.

If you change "strictNullChecks" to true, the complaint disappears (the type is correctly narrowed down from number | string | null | undefined to string | null | undefined).

  • Related