簡體   English   中英

TypeScript:使用字符串文字時的類型推斷

[英]TypeScript: Type inference when using string literals

請查看以下 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 游樂場: 演示

您也需要在整個config2上投射const

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"

現在的問題是:是否有可能以某種方式更改類型 V2 =... 的定義,它推斷鍵入“someOtherValue”而不是一般的字符串?

是的,您必須告訴 typescript 類型不會隨 const assertion 改變 您可以按照@satanTime 的建議將其應用於 value 道具或整個 object。

為什么? 因為 typescript 假設您可能會做以下事情。

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM