【发布时间】:2019-05-07 02:06:14
【问题描述】:
例如:
const map = { small: 1, large: 2 };
const closestSize = ['small', 'large'].find((size) => !!map[size]);
// errors Type 'undefined' cannot be used as an index type.ts(2538) but we know that either small or large will be found
return map[closestSize];
【问题讨论】:
-
map[closestSize!]或const closestSize = ['small', 'large'].find((size) => !!map[size])!; -
@TitianCernicova-Dragomir 试过了,我得到了
Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.ts(2322) -
@Toli 两个版本都可以工作:typescript-play.js.org/?noImplicitAny=false#code/… 和typescript-play.js.org/?noImplicitAny=false#code/… 你注意到
!,对吧?我提到它是因为它很容易错过..
标签: typescript