parseArgs,在文档中提供了完全相同的示例代码,会抛出类型错误。

huangapple go评论160阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月18日 22:53:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定