简体   繁体   中英

TypeScript: Returned type when accessing undefined key on object is wrong?

I noticed unexpected types when using objects with variable keys in TypeScript.

Given the following code

type MyType = {
  [x: number] : number
}

const o : MyType = {
  0: 1,
}

const a = o[0]; // Return type correctly identified as number
const b = o[1]; // Return type should be undefined and compiler should not allow this

I noticed that the type of an object access using [...] is not correctly detected when the object type is defined using the [x: number] syntax for variable keys.

VSCode shows me that both a and b have type number . Shouldn't the type be number | undefined number | undefined instead because it can happen that a key is undefined? When logging a and b to the console, a is a number while b is undefined .

The problem becomes more serious when an object of type MyType is passed to a function and this function accesses a key in this object and then does something like this:

function fun(o: MyType) : number {
   return o[10000] ?? null  // can be number or null at runtime
}

No error is shown. But when the code is run, o[10000] is undefined and therefore the return value is null which is not a valid number. Imagine using this return value to perform further computations that are all based on the assumption that is is a valid number. This would lead to runtime errors that should have been detected by the compiler (if I don't understand something completely wrong, I am new to TS)

(TypeScript used in these examples is configured by create-react-app, I did not change any settings)

Shouldn't the type be number | undefined instead because it can happen that a key is undefined?

You have that option if you want; just define it as:

type MyType = {
  [x: number] : number | undefined
}

This can be useful if you expect to be accessing random properties that might not exist.

On the other hand though, it's fairly common to use objects in a more disciplined manner that avoids the possibility of accessing nonexistent properties. For example, if you're commonly writing code that uses Object.keys(o) or for... in to decide what properties to access, then you're already doing the work to make sure it exists, and it may get frustrating to have typescript always tell you it might be undefined.

Add "noUncheckedIndexedAccess": true to your tsconfig.json complierOptions object

Your MyType defines an index accessor that allows any number to be used as an accessor on an object:

type MyType = {
  [x: number] : number
}

This means that, as far as type safety, any number can be used to access the object using the index accessor, similar to an array.

Your object only defines a single property - but the type checker (compilation time) is not looking at your object, which is created a runtime. All the type checker knows about is MyType , and any number is a valid value to use to index any object whose type is or extends MyType .

You have to remember that your object, at runtime, is still just a regular old JavaScript object, and nothing about TypeScript applies once the code is compiled and running.

If you're looking to define a type with a set number of properties, then you should construct your type with a set number of properties instead of using an index accessor:

interface MyType {
  0: number
}

const o: MyType = { 0: 1 } // valid
const o2: MyType = { 1: 1 } // type checking error
o[0] // valid
o[1] // type checking error 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM