I have an array of objects that can be null or a Gamepad:
let pads : (Gamepad | null)[] = navigator.getGamepads()
And if the first entry is a Gamepad (and not null) I want to execute some code
let pad: Gamepad | null = gamepads[0]
if (pad) {
myOtherCode(pad)
}
This null-check works but I have to create an extra temporary variable. Is there a way to just null-check the first entry of the array directly?
if (gamepads[0]) {
myOtherCode(gamepads[0])
}
Argument of type 'Gamepad | null' is not assignable to parameter of type 'Gamepad'. Type 'null' is not assignable to type 'Gamepad'
My other code is just a function that expects a gamepad:
function myOtherCode(g:Gamepad) {
console.log(g)
}
This is a compiler bug in which types with index signatures (like arrays) are not properly type guarded on index property access (with the square bracket). It is not clear when this will be fixed (the issue currently, as of May 11 2019, says "Milestone: TypeScript 3.5", but that version will be coming out shortly, so I kind of doubt that milestone will be achieved). The workaround, as you note, is to assign to a new variable and check that. Hope that helps; good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With