javascript - 为什么 typescript 提示对象的键是未定义的,即使前一个命令为该键设置了一个值?

标签 javascript typescript undefined

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] 赋值?

我怎样才能避免它?

enter image description here

检查示例 here

最佳答案

我明白为什么它会得到那个。

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

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


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 将始终为字符串类型

关于javascript - 为什么 typescript 提示对象的键是未定义的,即使前一个命令为该键设置了一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66930004/

相关文章:

javascript - 如何在 Javascript 中单击按钮时添加 div 元素?

angular - ion-label 在 Ionic2 中不显示整个文本

TypeScript - getOwnPropertyNames() - 构造函数属性与 Getter/Setter

PHP 通知 : Undefined offset: 1 with array when reading data

javascript - JQuery val 返回未定义

java - 为什么我收到错误 "the Method Is Undefined for the type"?

javascript - NextJS .prepare() 实际上做了什么?

javascript - 将参数传递给 jQuery 中的事件处理程序

javascript - 从 Meteor 模板注入(inject) Javascript

reactjs - 如何使用 React useRef 避免 TypeScript 错误?