【问题标题】:How to generate a warning/error when using non-string-variables inside string interpolation?在字符串插值中使用非字符串变量时如何生成警告/错误?
【发布时间】:2020-10-11 01:23:44
【问题描述】:

TypeScript 不会为以下代码产生任何错误:

const maybe_a_string: undefined | string = undefined;
const false_or_string: false | string = false;

// I'd like the following to produce an error/warning...
const message_string = `Some readable string info should be here: ${maybe_a_string}  ${false_or_string}`;

是否有某种设置我可以打开,或者简单的替代方法来编写最后一行,以警告我尝试在这样的字符串中使用非字符串变量? (但不需要为要单独断言的每个子字符串添加额外的代码行)

我猜它会很好地对待它们,因为某些类型,如 bools、numbers 和 misc 对象有一个 .toString() 方法...

但特别是在 undefined 的情况下(实际上没有 .toString() 方法) - 你在那里有一个错误是很常见的,因为你只有一次真正想看到字符串“另一个字符串中的 undefined" 用于调试目的。但是在野外有很多这样的错误,最终用户会无意中看到诸如“hello undefined”之类的东西。

【问题讨论】:

  • 这听起来像是一个 linter 的工作,但它很难搜索,规则可能还不存在
  • 遵循与"" + expr相同的规则,定义明确。
  • 但是在野外有很多这样的错误 - 没有野外,这是我们编写的代码,你可以修复它;)

标签: string typescript substring concatenation tostring


【解决方案1】:

我个人会通过将字符串模板变成一个函数来处理这个问题。这样你就可以指定参数必须是字符串。

const createMessageString = (first: string, second: string): string => {
    return `Some readable string info should be here: ${first}  ${second}`;
}

const message_string = createMessageString( maybe_a_string, false_or_string );
// will give an error unless types are refined

【讨论】:

    猜你喜欢
    • 2014-01-24
    • 2012-10-26
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多