【发布时间】:2020-05-10 23:13:28
【问题描述】:
请查看以下 TypeScript 代码。 很明显,类型推断的行为就像 cmets 中描述的那样。
现在的问题是:是否有可能以某种方式更改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
【问题讨论】:
标签: typescript typescript-typings