TypeScript:使用字符串文字时的类型推断

标签 typescript typescript-typings

请查看以下 TypeScript 代码。 很明显,类型推断的行为与评论中描述的一样。

现在的问题是:是否有可能以某种方式更改 type V2 = ... 的定义,它推断类型 "someOtherValue" 而不是string 一般不再?

据我了解 TypeScript 的类型推断,这是绝对不可能的……但谁知道呢,也许我错了。 为了安全起见,我最好向 TypeScript 社区寻求帮助。谢谢。

const config1 = { value: 'someValue' as const } 

type K1 = keyof typeof config1      // type K1: "value" (not string in general)
type V1 = (typeof config1)['value'] // type V1: "someValue" (not string in general)

const config2 = { value: 'someOtherValue' } 

type K2 = keyof typeof config2      // type K2: "value" (not string in general)
type V2 = (typeof config2)['value'] // type V2: string

TypeScript Playground :Demo

最佳答案

你也需要在整个 config2 上转换 const

const config2 = { value: 'someOtherValue' } as const;

否则它总是字符串。


用 key 访问

const config1 = { value: 'someValue' as const } 

type K1 = keyof typeof config1      // type K1: "value" (not string in general)
type V1 = (typeof config1)['value'] // type V1: "someValue" (not string in general)

const config2 = { value: 'someOtherValue' } as const;

type K2 = keyof typeof config2 // type K2: "value" (not string in general)
type V2 = (typeof config2)[K2] // type V2: "someOtherValue"

关于TypeScript:使用字符串文字时的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61711818/

相关文章:

javascript - 如何在不创建数组的情况下使用 NgFor 来生成矩阵 UI 模式

typescript - 未推断可选泛型类型

javascript - typescript 可选链接结合三元运算符解析错误

TypeScript: key 索引签名仅适用于所有未定义的属性

typescript - 如何根据数组的值定义类型?

javascript - 如何在 Ngoninit() 中使用增量运算符?

javascript - 如何访问 javascript/typescript 中的重复项计数

typescript :基于输入值(枚举)的函数返回类型

typescript - 在 TypeScript 中,使第二个参数自动完成取决于第一个参数中的字符串

javascript - 我如何将接口(interface)应用于 typescript 中的匿名回调函数