首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将yargs与Typescript一起使用

将yargs与Typescript一起使用
EN

Stack Overflow用户
提问于 2020-01-17 12:10:55
回答 1查看 2.2K关注 0票数 0

我不明白当我将options抽象为一个变量(或者甚至从另一个文件导入)时,Typescript会抱怨:

代码语言:javascript
复制
Argument of type '{ exclude: { type: string; required: boolean; description: string; default: never[]; alias: string; }; someOtherFlag: { type: string; required: boolean; description: string; default: never[]; }; }' is not assignable to parameter of type '{ [key: string]: Options; }'.
  Property 'exclude' is incompatible with index signature.
    Type '{ type: string; required: boolean; description: string; default: never[]; alias: string; }' is not assignable to type 'Options'.
      Types of property 'type' are incompatible.
        Type 'string' is not assignable to type '"string" | "number" | "boolean" | "array" | "count" | undefined'.ts(2345)
代码语言:javascript
复制
import * as yargs from 'yargs';

const options = {
  exclude: {
    type: 'array',
    required: false,
    description: 'Files to exclude',
    default: [],
    alias: 'e'
  },
  someOtherFlag: {
    type: 'array',
    required: false,
    description: 'Another example flag'
    default: []
  }
};

// throws Typescript error
const cliOptions = yargs.options(options).argv;
EN

回答 1

Stack Overflow用户

发布于 2020-01-17 15:17:12

执行以下操作之一(第一个是使用as const):

代码语言:javascript
复制
const options = {...} as const 

// or 
const options = {
  exclude: { type: "array"  as "array", ...},
  someOtherFlag: { type: "array" as "array", ...}
} 

解释:

在查看其类型declaration时,传递给yargs.options(options)options文本似乎没有问题。

有一点很重要,为什么它在当前表单中不起作用:options文本类型变宽了。因此,type: 'array'变成了type: stringyargs.options期望一个用于typestring literal,所以在这里它失败了。

如果你想阅读更多关于这个主题的内容,那么前面提到的类型扩展基本上是由于immutability check和缺少显式类型而发生的。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59781071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档