我不明白当我将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;发布于 2020-01-17 15:17:12
执行以下操作之一(第一个是使用as const):
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: string。yargs.options期望一个用于type的string literal,所以在这里它失败了。
如果你想阅读更多关于这个主题的内容,那么前面提到的类型扩展基本上是由于immutability check和缺少显式类型而发生的。
https://stackoverflow.com/questions/59781071
复制相似问题