【发布时间】: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