gpt4 book ai didi

typescript - 如果在 typescript 中未定义,如何设置变量?

转载 作者:行者123 更新时间:2023-12-03 13:45:07 29 4
gpt4 key购买 nike

我正在尝试设置 undefined variable 值,但是,在尝试使用普通javascript方法时遇到错误。

Block-scoped variable 'x' used before its declaration.



使用 typescript 设置 undefined variable 时的最佳方法是什么?
let x = (typeof x === 'undefined') ? def_val : x;

最佳答案

TypeScript可以告诉您x绝对未定义,因为它是一个块作用域变量,您可以看到整个块。
如果您比编译器更了解,则可以分开以下几行:

const def_val = 'default';

let x: string;
x = (typeof x === 'undefined') ? def_val : x;
但是您可能要考虑在您的情况下如何可能无法定义块范围变量(也许您的代码并不像问题中的示例那么简单)。
常见的用例将更像是:
const def_val = 'default';

function work(y: string) {
let x = (typeof y === 'undefined') ? def_val : y;
}
您还可以添加更严格的编译器选项,以使在很多情况下不太可能未定义该值。
速记
还有一个简短的虚假提示可能有用:
const def_val = 'default';

function work(y: string) {
let x = y || def_val;
}
这将用默认值替换 undefinednull0(零)或 ''

关于typescript - 如果在 typescript 中未定义,如何设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328862/

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