Croad Langshan
Croad Langshan

Reputation: 2800

Why is it possible to index an object that has type never?

With strict enabled in tsconfig.json, why does tsc not issue an error when indexing an object of type never?

const mystery = ({ foo: 1 } as never)

console.log(mystery['foo'])  // no error
console.log(mystery.foo)  // Property 'foo' does not exist on type 'never'.

export {}

Playground example

Upvotes: 3

Views: 113

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

It's bug #41021:

'never' (and probably 'void') shouldn't be silently indexable types

DanielRosenwasser commented on Oct 10, 2020

let x = [1, 2, 3, 4].forEach(x => { console.log(x));
x["hello"] = 123;

Expected: an error that x is possibly void or something Actual: no errors


DanielRosenwasser commented on Oct 10, 2020

Actually, never seems to suffer from the same issue..

The TypeScript team are actively fixing it, but no fix is available yet.

Here's a simpler replication:

declare let mystery: never;

console.log(mystery["foo"]);    // No error
console.log(mystery.foo);       // Property 'foo' does not exist on type 'never'.

Upvotes: 1

Related Questions