为什么打字稿抱怨对象的键是未定义的,即使前一个命令为该键设置了一个值?

Why typescript complains object's key is undefined even if the previous command sets a value to that key?

type MaybeThereIsAValue = {
  [p: string]: string | undefined
}

...

let bar: MaybeThereIsAValue = {};
const key = "carpe";
bar[key] = "diem";

const why = bar[key];
// why is string | undefined

为什么 why string | undefined 是因为我在上一行中确实为 bar[key] 赋值?

我怎样才能避免它?

检查示例here

我明白为什么会这样。

那是因为tsconfig的strictNullChecks设置为true,默认为false,

const key = 'carpe'是在TS编译成JS后才执行的,所以TS不知道是哪个键


strictNullChecks:类型检查时,考虑null和undefined。


所以如果你想解决这个问题,我的两个解决方案是:

1.将 tsconfigstrictNullChecks 设置为 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 将始终为字符串类型