gpt4 book ai didi

javascript - 是不是类似于 Flow 中 TypeScript 的非空断言运算符?

转载 作者:行者123 更新时间:2023-11-29 23:18:53 27 4
gpt4 key购买 nike

Non-null assertion operator

例子:

function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}

最佳答案

不完全相似,但您可以添加 type casting expression在 let 行之前加上这样的内容:

function processEntity(e?: Entity) {
validateEntity(e);
(e: Entity);
let s = e.name; // Assert that e is non-null and access name
}

但如果 e 为 null,则不提示错误对您没有帮助,所以我认为使用 if 是最好的选择:

function processEntity(e?: Entity) {
validateEntity(e);
if (e) {
let s = e!.name; // Assert that e is non-null and access name
}
}

关于javascript - 是不是类似于 Flow 中 TypeScript 的非空断言运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51520817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com