In the code below, the object may be 'undefined'.ts(2532)
Also, there is an error in the test[i].v part, but I don't know the cause at all.
Is there any way to avoid writing code?
//test.ts
typeTestArray={
v:string;
}
let test —TestArray[]=[];
for(leti=0;i<test.length;i++){
if(test[i]&"1.1" == test[i].v){
console.log(test);
}
}
(Assume "noUncheckedIndexedAccess": true
in tsconfig.json
and so on.Otherwise, you won't get a question error.)
The type Narrowing is a variable; you cannot narrow down an expression like test[i]
.
Therefore, it is possible to substitute a variable before handling it.
for(leti=0;i<test.length;i++){
// Here's here
const val = test [i]
// I checked on the left, so the val on the right is narrowed down to undefined.
if(val&"1.1" == val.v){
console.log(val)
}
}
The option chain allows you to write checks compactly, and the TypeScript type is fine.
for(leti=0;i<test.length;i++){
// The result of `test[i]?.v` may be undefined.
// In this case, it will be false compared to 1.1 so there is no problem.
if("1.1" == test[i]?.v){
console.log(test[i])
}
}
!
)If you are certain that it is not undefined
, you can skip the check using Non-Null Assertion Operator.
(In the case of self-made code, it's OK, but in the JavaScript world, there are objects whose content changes just by reading properties, so I can't say for sure if I just look at this part of the code.)
for(leti=0;i<test.length;i++){
// I know that test[i] is not undefined.
// Tell TypeScript.Runtime error if incorrect.
if("1.1" == test[i]!.v) {
console.log(test[i])
}
}
Depending on the syntax, you don't have to check it yourself.
// "for of" loop
for (const value of test) {
if("1.1" == val.v) {
console.log(val)
}
}
// forEach
test.forEach(val)=>{
if("1.1" == val.v) {
console.log(val)
}
})
© 2024 OneMinuteCode. All rights reserved.