te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - TypeScript: Returned type when accessing undefined key on object is wrong? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript: Returned type when accessing undefined key on object is wrong? - Stack Overflow

programmeradmin6浏览0评论

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 piler 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 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 bees 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 putations 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 piler (if I don't understand something pletely wrong, I am new to TS)

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

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 piler 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 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 bees 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 putations 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 piler (if I don't understand something pletely wrong, I am new to TS)

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

Share Improve this question asked Apr 29, 2020 at 2:48 Simon HessnerSimon Hessner 1,8372 gold badges26 silver badges50 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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

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 mon to use objects in a more disciplined manner that avoids the possibility of accessing nonexistent properties. For example, if you're monly 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.

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 (pilation 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 piled 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 
发布评论

评论列表(0)

  1. 暂无评论