typescript 中 type 'null' is not assignable to type 问题解决
使用联合类型来解决 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 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
在 angularjs 中设置 select from typescript 的默认选项值
发布时间:2023/04/14 浏览次数:132 分类:angular
-
本教程提供了在 angularjs 中从 typescript 中设置 html 标记选择的默认选项的解释性ag捕鱼王app官网的解决方案。
在 angular 中使用 typescript 的 getelementbyid 替换
发布时间:2023/04/14 浏览次数:259 分类:angular
-
本教程指南提供了有关使用 typescript 在 angular 中替换 document.getelementbyid 的简要说明。这也提供了在 angular 中 getelementbyid 的最佳方法。
在 typescript 中使用 try..catch..finally 处理异常
发布时间:2023/03/19 浏览次数:385 分类:
-
本文详细介绍了如何在 typescript 中使用 try..catch..finally 进行异常处理,并附有示例。
发布时间: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官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。