简体   繁体   English

当 function 参数提供空字符串时,如何告诉 Typescript 使用默认值?

[英]How can I tell Typescript to use the default value when an empty string is provided as function parameter?

In Typescript, when assigning a default value to a parameter of type string , the empty string counts as something and the default value is not used.在 Typescript 中,当为string类型的参数分配默认值时,空字符串计为某事,不使用默认值。

This makes sense, but in some cases, I'd like to change that:这是有道理的,但在某些情况下,我想改变它:

function greet (name?:string = 'visitor') {
  console.log(`Hello ${name}`)
}
greet('Gromit') // logs "Hello Gromit"
greet() // logs "Hello visitor"
greet('') // logs "Hello " <--- How can I get the default value in this case too?

Does Typescript perhaps have a feature, which I am not finding, to help define when I want the default value to apply? Typescript 是否可能具有我没有找到的功能来帮助定义何时应用默认值?

I have been using what I consider to be a workaround, for now:我一直在使用我认为是一种解决方法,现在:

const defaultName = 'visitor'
function greet (name?:string = defaultName) {
  const finalName = name || defaultName
  console.log(`Hello ${finalName}`)
}

But I would rather use something cleaner and more idiomatic to Typescript and I would be surprised if a better pattern doesn't exist.但我宁愿对 Typescript 使用更干净、更惯用的东西,如果不存在更好的模式,我会感到惊讶。

To be clear, I would have expected to find a way to do this within that part of the code responsible for defining the function parameters: function greet (/* here */) {}需要明确的是,我希望在负责定义 function 参数的代码部分中找到一种方法来执行此操作:function greet (/* here */) {}

The proposed solutions introduce code outside of this section the same as I do in my workaround.建议的解决方案在本节之外引入代码,就像我在解决方法中所做的一样。

Thanks for any pointers!感谢您的任何指点!

There's no way to define this condition inside the function arguments.无法在 function arguments 中定义此条件。 The cleanest way I can think of is simply to check and replace the value inside the function body:我能想到的最干净的方法就是检查和替换 function 体内的值:

function greet(name?: string) {
  name = name || 'visitor'
  // other code
}

A better pattern doesn't exist, because it would conflict with the perfectly reasonable behavior that "" overrides the default non-empty value.不存在更好的模式,因为它会与""覆盖默认非空值的完全合理的行为相冲突。

You have two different ways of specifying default-like behavior, one of which is an absent value, and one of which provides a value if passed an empty/falsy value.您有两种不同的方式来指定类似默认的行为,其中一种是不存在的值,另一种是在传递空/假值时提供值。 These might happen to result in the same value, but there isn't a more-concise pattern to represent this in the function signature or implementation.这些可能碰巧产生相同的值,但在 function 签名或实现中没有更简洁的模式来表示这一点。

The only modification I would make to MaartenDev and Vojtěch Strnad's answers would be to document the default value in JSDoc, which might accomplish your goal of IDE integration.我将对 MaartenDev 和 Vojtěch Strnad 的答案进行的唯一修改是在 JSDoc 中记录默认值,这可能会实现您的 IDE 集成的目标。 (Unfortunately, even then JSDoc's optional/default value support [name="visitor"] isn't visible in TypeScript Playground or VSCode.) (不幸的是,即使这样, JSDoc 的可选/默认值支持[name="visitor"]在 TypeScript Playground 或 VSCode 中也不可见。)

/**
 * Greets a person.
 *
 * @param [name] Name to greet. "visitor" if falsy or absent.
 */
function greet(name?: string) {
  name = name || 'visitor'
  // other code
}

Playground Link 游乐场链接

Observation: As you are initializing a default value to name parameter, it makes that parameter optional.观察:当您将默认值初始化为name参数时,它使该参数成为可选的。 Hence, no need to add Question mark (?) explicitly as it will through a below compilation error.因此,无需显式添加问号 (?),因为它会通过以下编译错误。

Parameter cannot have question mark and initializer.参数不能有问号和初始化器。

Regarding the issue you are facing, You can get rid from that by using Conditional (ternary) operator关于您面临的问题,您可以使用Conditional (ternary) operator摆脱它

function greet (name:string = 'visitor') {
    console.log(`Hello ${name}`)
}
 
greet('' ? '' : undefined) // Hello visitor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM