请看下面的TypeScript代码。很明显,类型推断的行为与注释中描述的类似。
现在的问题是:是否有可能以某种方式更改type V2 = ...的定义,即它推断输入"someOtherValue"而不是一般的string?
据我所知打字稿的类型推断这绝对不可能..。但谁知道呢也许我错了。为了安全起见,我最好向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: stringTypeScript游乐场:演示
发布于 2020-05-10 12:22:17
您也需要将const转换为整个config2。
const config2 = { value: 'someOtherValue' } as const;否则它将永远是字符串。
带密钥访问
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"发布于 2020-05-10 12:41:09
现在的问题是:是否有可能更改V2 =.类型的定义?在某种程度上,它推断输入"someOtherValue“而不是字符串在一般情况下?
是的,您必须告诉打字本,类型不会随着const断言而改变。。您可以按照@satanTime的建议将其应用于值支柱或整个对象。
为什么?因为类型记录假设你可能会做下面的事情。
const config2 = { value: 'someOtherValue' }
config2.value = "something different"使用const断言,应用类型检查器可以决定进行类型缩小。
const config1 = { value: 'someValue' as const }
config1.value = "test" // Type '"test"' is not assignable to type '"someValue"'.
const config2 = { value: 'someOtherValue' } as const
config2.value = "test" // Cannot assign to 'value' because it is a read-only property.https://stackoverflow.com/questions/61711818
复制相似问题