Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array: Object is possible 'undefined'. #47167

Closed
infacto opened this issue Dec 16, 2021 · 3 comments
Closed

Array: Object is possible 'undefined'. #47167

infacto opened this issue Dec 16, 2021 · 3 comments

Comments

@infacto
Copy link

infacto commented Dec 16, 2021

Bug Report

πŸ”Ž Search Terms

array is possible undefined

πŸ•— Version & Regression Information

Tested with typescript@next (4.6.0-dev.20211216). I initially came from 4.2.4.

⏯ Playground Link

Playground does not work for this.

πŸ’» Code

export const myFunc = (): void => {
  const bytes: number[] = new Array<number>(16).fill(0);
  bytes[0] = bytes[6] & 0xf0;
};

πŸ™ Actual behavior

I get an error Object is possiible 'undefined'.

πŸ™‚ Expected behavior

I know that new Array(n) generates an array with length and undefined items. But I also use fill and fixed types. I don't know how to avoid this error. Cast to number[] does also not work (unsafe cast).

demo

tsconfig.json (click to expand)
{
  "compilerOptions": {
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "target": "ES2018",
    "module": "commonjs",
    "moduleResolution": "Node",
    "importHelpers": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "rootDir": "src",
    "incremental": true,
    "tsBuildInfoFile": "node_modules/.cache/.tsbuildinfo",
    "noErrorTruncation": true
  },
  "include": ["src"],
  "exclude": ["./**/*.spec.ts", "tests"]
}
@MartinJohns
Copy link
Contributor

Playground does not work for this.

It does, you just need to enable noUncheckedIndexAccess: Playground link

And then it's basically the same as #46922. The type number[] has no notion of "index 6 is always defined".

@infacto
Copy link
Author

infacto commented Dec 16, 2021

Ok thanks. Disabling noUncheckedIndexedAccess works.
But are there other options? I mean the array declaration is safe without undefined items withing the given length (in this case). Can I force the not nullish type like with ! or something like that?

@infacto infacto closed this as completed Dec 16, 2021
@fatcerberus
Copy link

Sure, if you know for sure the value won’t be undefined then just write bytes[6]!.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants