'TypeScript literal number type not being calculated [closed]
I'm confused with such behavior: TS Playground.
type N = 1 | -1 | 0
// Type 'number' is not assignable to type 'N'.
function test_3(arg: N): N {
return Math.abs(arg)
}
// OK!?
function test_5(arg: N): N {
return (-arg * 4) as N
}
Solution 1:[1]
TypeScript is not smart enough to understand that Math.abs() would return 1 when given -1 or 0 when given 0. All it knows is that return type of Math.abs() is number and number does not extend the return type N of the function test_3.
So if you tell TypeScript that you are certain that Math.abs() returns a member of N (with as N) TypeScript will not show an error.
Solution 2:[2]
Math.args returns a number. The function is not able to understand that as your entry is of type N, then your output will also be of type N. For it, it will always be a number as output.
That's why you have the first error indicating that a number can not be considered as a type N.
For the second case, you explicitly tell Typescript with the as that your number is actually of type N, so even if that's wrong, typescript is ok with that because it can easily consider a number as a N type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tobias S. |
| Solution 2 | Rémi Mondenx |
