英文:
parseArgs, throws type error exact same sample code in docs
问题
import { parseArgs } from 'node:util';
const args = [];
const options = {
t: {
type: 'string'
}
}
const { values, positionals } = parseArgs({ args, options });
这段代码来自文档中的示例代码,报错如下:
src/main.ts:13:51 - error TS2322: 类型 '{ t: { type: string; }; }' 不能分配给类型 'ParseArgsOptionsConfig'。
属性 't' 与索引签名不兼容。
类型 '{ type: string; }' 不能分配给类型 'ParseArgsOptionConfig'。
属性 'type' 的类型不兼容。
类型 'string' 不能分配给类型 '"string" | "boolean"'。
13 const { values, positionals } = parseArgs({ args, options })
~~~~~~~
这是什么意思?
编辑
如果我将 t: 'string'
显式转换为 t: 'string' as 'string'
,则不会报错。如果有人能更好地解释这个问题,我会很感激。
英文:
import { parseArgs } from 'node:util'
const args = []
const options = {
t: {
type: "string"
}
}
const { values, positionals } = parseArgs({ args, options })
This code taken from the example code in the documentation throws this:
src/main.ts:13:51 - error TS2322: Type '{ t: { type: string; }; }' is not assign
able to type 'ParseArgsOptionsConfig'.
Property 't' is incompatible with index signature.
Type '{ type: string; }' is not assignable to type 'ParseArgsOptionConfig'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"string" | "boolean"'.
13 const { values, positionals } = parseArgs({ args, options })
~~~~~~~
What the hell does this mean?
Edit
If I explicitly cast t: 'string'
to
t: 'string' as 'string'
it passes. If anyone can explain this problem better, I'd appreciate it.
答案1
得分: 1
另一个答案提供了正确的问题诊断:TypeScript 推断 type
键包含任何字符串,而不是特定的 "string"
或 "boolean"
,而这正是类型所需要的。
但更好的解决方法是在选项定义中添加 as const
:
const options = {
t: {
type: "string"
}
} as const
这将告诉 TypeScript 更狭窄地推断类型,从而使类型正常工作。这样做还可以获得更好的结果值类型推断。
英文:
The other answer gives the correct diagnosis of the problem: TypeScript infers the type
key as holding any string, rather than specifically "string"
or "boolean"
, which is what the types require.
But a better fix to this is to add as const
to the options definition:
const options = {
t: {
type: "string"
}
} as const
That will tell TypeScript to infer the type more narrowly, which will make the types work. And by doing so you will get better type inference for the resulting value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论