请查看以下 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/