typescript 中 type 'null' is not assignable to type 问题解决-ag捕鱼王app官网

当前位置:ag捕鱼王app官网 > > web前端 >

typescript 中 type 'null' is not assignable to type 问题解决

作者:迹忆客 最近更新:2023/01/08 浏览次数:

使用联合类型来解决 typescript 中的“type 'null' is not assignable to type”错误,例如 name: string | null。 特定值的类型必须接受 null,因为如果不接受并且您在 tsconfig.json 中启用了 strictnullchecks,则类型检查器会抛出错误。

以下是错误发生方式的 2 个示例。

// 函数返回值设置为对象
function getobj(): record {
  if (math.random() > 0.5) {
    //  错误 type 'null' is not assignable to type
    // 'record'.ts(2322)
    return null;
  }
  return { name: 'tom' };
}
interface person {
  name: string; // 名称属性设置为字符串
}
const obj: person = { name: 'tom' };
// type 'null' is not assignable to type 'string'.ts(2322)
obj.name = null;

第一个示例中的函数返回 null 值或对象,但我们没有指定该函数可能返回 null。

第二个示例中的对象具有 name 属性的字符串类型,但我们试图将属性设置为 null 并得到错误。

可以使用联合类型来解决错误。

function getobj(): record | null {
  if (math.random() > 0.5) {
    return null;
  }
  return { name: 'tom' };
}
interface person {
  // 👇  使用 union
  name: string | null;
}
const obj: person = { name: 'tom' };
obj.name = null;

我们使用联合类型将函数的返回值设置为具有字符串键和值的对象或 null。

这种方法允许我们从函数返回一个对象或空值。

在第二个示例中,我们将对象中的 name 属性设置为字符串类型或 null

现在我们可以将属性设置为 null 而不会出现错误。

如果必须访问 name 属性,例如 要对其调用 tolowercase() 方法,必须使用类型保护,因为该属性可能为 null。

interface person {
  // 使用 union
  name: string | null;
}
const obj: person = { name: 'tom' };
// error: object is possibly 'null'.ts(2531)
obj.name.tolowercase();

可以用一个简单的类型保护来解决这个问题。

interface person {
  // 使用 union
  name: string | null;
}
const obj: person = { name: 'tom' };
if (obj.name !== null) {
  // 现在 obj.name 是字符串
  console.log(obj.name.tolowercase());
}

可以通过在 tsconfig.json 文件中将 strictnullchecks 设置为 false 来屏蔽“type 'null' is not assignable to type”错误。

{
  "compileroptions": {
    "strictnullchecks": false,
    // ...  重置
  }
}

当 strictnullchecks 设置为 false 时,语言会忽略 null 和 undefined。

这是不可取的,因为它可能会导致运行时出现意外错误。

当我们将 strictnullchecks 设置为 true 时,null 和 undefined 有它们自己的类型,并且在需要不同类型的值时使用它们会出现错误。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

发布时间:2023/03/19 浏览次数:254 分类:

本教程指南通过特定的实现和编码示例深入了解了 typescript 中 declare 关键字的用途。

发布时间:2023/03/19 浏览次数:962 分类:

本篇文章演示了类的 get 和 set 属性以及如何在 typescript 中实现它。

在 typescript 中格式化日期和时间

发布时间:2023/03/19 浏览次数:269 分类:

本教程介绍内置对象 date() 并讨论在 typescript 中获取、设置和格式化日期和时间的各种方法。

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图