Argument of type 'number | undefined' is not assignable to parameter of type 'number'.

How fix this?
10 Replies
Jochem
Jochem12mo ago
add a default values with ?? 0 at the end, or redefine the signature for convertToMinuteSeconds to deal with undefined
Nikita
Nikita12mo ago
Jochem
Jochem12mo ago
please paste your code in acode block instead of sharing screenshots I'm not typing everything out, but I can show you where to put it if I can copy-paste it
Nikita
Nikita12mo ago
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current ??.currentTime))
}
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current ??.currentTime))
}
Jochem
Jochem12mo ago
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current?.currentTime ?? 0))
}
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current?.currentTime ?? 0))
}
Nikita
Nikita12mo ago
Thank you
Jochem
Jochem12mo ago
?? is called the nullish coalescing operator, it returns the first value if it's not nullish (so null or undefined), and the second value if the first one is nullish https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
Queequeg
Queequeg12mo ago
@jochemm I was going to suggest using a logical OR like so:
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current?.currentTime || 0))
}
const onTimeUpdate = () => {
setCurrentTime(() => convertToMinuteSeconds(videoRef.current?.currentTime || 0))
}
Do you think the ?? operator better or about the same as || in situations like these? Given, of course, that a 0 will fall through to default as 0 in this case. I have not used ?? in code before, I have used || a ton.
Jochem
Jochem12mo ago
|| coerces the left hand side to boolean, which means you're checking for falseish instead of nullish the string '0', empty string, NaN, all convert to false the error in this case is saying that the value of the expression is either undefined or a number, so it's going to narrow down to what you said, 0 falling through to the default, but in general I prefer using ?? because it's narrower and more explicit when you're reading the code
Queequeg
Queequeg12mo ago
I learn something new every day! Thanks. While reading the documentation, I also learned that combining || and ?? in a series of checks will not work without parenthesis. This is something to keep in mind as I frequently do this too.