1

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]
0

1 Answer 1

3

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

Link to playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.