3

Found it here

export function convertToUnit (str: string | number | null | undefined, unit = 'px'): string | undefined {
  if (str == null || str === '') {
    return undefined
  } else if (isNaN(+str!)) { // **** THIS LINE ****
    return String(str)
  } else {
    return `${Number(str)}${unit}`
  }
}
Jesse Carter
  • 17,976
  • 7
  • 55
  • 87
manidos
  • 2,852
  • 3
  • 22
  • 52
  • 2
    `+str` tries to convert a string (or anything, really) to a number and yields NaN if it could not convert. `isNaN` (is not a number, which checks for `NaN` type) checks if the conversion was successful. – pascalpuetz Sep 15 '20 at 16:35
  • @pascalpuetz, oh, makes sense, thank you, sir! – manidos Sep 15 '20 at 16:40

2 Answers2

5

The expression +str! combines the (JavaScript operator) unary plus with the (TypeScript-exclusive operator) non-null assertion operator.

The ! asserts that str is not null nor undefined before the + is done. But, due to the str == null test done above, the str cannot be null nor undefined at that point: the assertion is unnecessary.

So, it's equivalent to

+str

which casts str to a number. This numeric value is then passed to isNaN, which will return true if the value is NaN, and will otherwise return false.

CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
  • It might also be worth noting that the `!` is a TypeScript feature. The usage of the `+` operator is standard JavaScript and not something specific to TypeScript. – Bart Hofland Sep 15 '20 at 16:41
2

The +, or unary plus operator, converts an object (str in this case) to a number. It's similar to parseInt or parseFloat but not exactly the same. You can read more about it in this answer.

The ! asserts that str isn't null, to suppress any warnings that the compiler would otherwise give. You can read more here.

If str is not a number, then the + operation will return 'Not a Number', or NaN. isNaN will return true if NaN was returned, or false if str was a valid number.

Andy Vaal
  • 433
  • 7
  • 12