0

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

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)
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;
4

1 回答 1

3

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

const options = {...} as const 

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

解释:

查看其类型声明时,您options传递给的文字yargs.options(options)似乎很好。

有一点很重要,为什么它不能以当前的形式工作:options字面量类型得到了扩展。结果,type: 'array'变为type: stringyargs.options需要一个字符串文字for type,所以在这里它爆炸了。

如果您想阅读有关此主题的更多信息,则提到的类型扩展基本上是由于不变性检查和缺乏显式类型而发生的。

于 2020-01-17T07:17:11.790 回答