【问题标题】:Set the types of the args from `process.argv` in TypeScript, without type assertions在 TypeScript 中从 `process.argv` 设置 args 的类型,没有类型断言
【发布时间】:2021-08-20 23:07:19
【问题描述】:

如何在 TypeScript 中设置从 process.argv 传入的参数的类型,而不使用类型断言?由于使用as 会强制使用类型,因此我想尽可能避免这种情况。

我现在拥有的:

type AppName = 'editor' | 'terminal';

function main(args: string[]): void {
  const app: AppName = args[0] as AppName;
}

main(process.argv.slice(2))

我想要什么(伪代码):

type AppName = 'editor' | 'terminal';

function main(args: string[]): void {
  // This doesn't actually work, since `in` doesn't work on `type`.
  if (!(args[0] in AppName)) {
    throw new Error("The first argument is not an app name.")
  }

  // The error: Type 'string' is not assignable to type 'AppName'.
  const app: AppName = args[0];
}

main(process.argv.slice(2))

有什么类似的可能吗?使用条件,TS 应该检测到我已经确保第一个 arg 是给定的应用程序名称之一,因此接受将其设置为类型为 AppName 的 var。

【问题讨论】:

    标签: typescript types assert argv assertion


    【解决方案1】:

    一种方法是使用类型保护。 Here's关于它的媒体文章

    我知道该解决方案,但您可能有更好的解决方案

    type AppName = 'editor' | 'terminal';
    
    function isAppName(toBeDetermined: any): toBeDetermined is AppName {
      if (toBeDetermined === 'editor' || toBeDetermined === 'terminal') {
        return true
      }
      return false
    } 
    
    function main(args: string[]): void {
      if (!isAppName(args[0])) {
        throw new Error("The first argument is not an app name.")
      }
    
      const app = args[0]; // const app: AppName
    }
    

    Here 是它的工作场所

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 2019-08-21
      • 2012-09-23
      • 2021-12-05
      • 2021-09-21
      • 2018-03-08
      • 2016-10-14
      相关资源
      最近更新 更多