【问题标题】:TypeScript: Type inference when using string literalsTypeScript:使用字符串文字时的类型推断
【发布时间】: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


    【解决方案1】:

    您也需要将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"
    

    【讨论】:

    • @ satanTime + @ JózefPodlecki: 写as const 不是在字符串本身之后而是在对象文字之后实际上是一个不错的主意。在我的实际用例中——这比那个简单的例子要复杂一些;-)——有一个函数可以获取一个大的配置对象作为参数,我不想在一些特殊的情况下写as const 几十次字符串...但是如果我只是在大型配置对象之后写一次as const,类型推断将按需要工作。非常感谢你们,你们真的帮了大忙:-)
    【解决方案2】:

    现在的问题是:是否有可能改变 type V2 = ... 在某种程度上,它推断输入“someOtherValue”和 一般不再串起来了?

    Yes, you have to tell typescript that type is not going to change with const assertion。您可以按照@satanTime 的建议将其应用于 value 道具或整个对象。

    为什么?因为打字稿假设你可能会做以下事情。

    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.
    

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多