Avatar ·

TypeScript中的null/nil是什么以及如何处理?

大家好!我开始学习TypeScript,对null和undefined的理解感到困惑。在JavaScript中,我习惯了null是显式设置的'空值',而undefined是未初始化的值。但在TypeScript中,是否还添加了nil类型?还是它们是一样的?

问题:在我的项目中,有一个函数从数据库返回数据。如果找不到记录,我想返回null,但TypeScript报错说函数可能返回undefined。我尝试使用严格模式(strictNullChecks: true)并明确指定返回类型为string | null,但在未检查的情况下访问结果时仍然遇到错误。

代码示例:

function findUser(id: number): string | null {
  const user = database.get(id);
  if (!user) return null;
  return user.name;
}

const userName = findUser(123);
console.log(userNam