在TypeScript中从`process.argv`设置args的类型,不带类型断言

问题描述 投票:0回答:1

我如何在TypeScript中设置从process.argv传入的args的类型,而不使用类型断言?因为使用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个回答
0
投票

一种方法是使用类型防护。 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是它的工作场所

© www.soinside.com 2019 - 2024. All rights reserved.