type MaybeThereIsAValue = {
[p: string]: string | undefined
}
...
let bar: MaybeThereIsAValue = {};
const key = "carpe";
bar[key] = "diem";
const why = bar[key];
// why is string | undefined
为什么是为什么
string | undefined
因为我实际上是在上一行中为 bar[key]
赋值?
我怎样才能避免它?
检查示例 here
最佳答案
我明白为什么它会得到那个。
那是因为strictNullChecks tsconfig 的设置为 true
,默认为 false,
而const key = 'carpe'
是在TS编译成JS后才执行的,所以TS不知道是哪个key。
strictNullChecks:类型检查时,考虑 null 和 undefined。
所以如果你想解决这个问题,我的两个解决方案是:
<强>1。将 tsconfig
的 strictNullChecks
设置为 false
<强>2。使用 !
non-null assertion operator
const why = bar[key]!;
让我们考虑一下这种情况:
let key = 'carpe';
bar[key] = 'diem';
// the next line would only be executed after the TS is compiled into JS.
key = 'test';
// that is to say TS does not know the key is 'test' or 'carpe'
// so `why` is type of string or undefined
const why = bar[key];
如果将 strictNullChecks
设置为 false,why
将始终为字符串类型
关于javascript - 为什么 typescript 提示对象的键是未定义的,即使前一个命令为该键设置了一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66930004/