Issue
In the following code, TS infer type of y
as string
while it's undefined
. Is it possible to fix it without explicitly define string|undefined
type for y
?
const x: string[] = []
const y = x[0]
Solution
Set "noUncheckedIndexedAccess": true
in tsconfig.json:
"Turning on noUncheckedIndexedAccess will add undefined
to any un-declared field in the type": https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess
// with noUncheckedIndexedAccess=true
const x: string[] = [];
const y = x[0];
y; // const y: string | undefined
Answered By - Julio Di Egidio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.