[英]typescript: make type that fits object literal values
鑒於此對象文字...
const views = {
default: 'DEFAULT',
user: {
home: 'HOME',
profile: 'PROFILE'
}
}
我想得到一個像下面這樣的類型,而不必以多種方式定義它,比如定義聯合類型,然后是一個嵌入了所有類型的對象文字
interface State {
view: `DEFAULT' | 'HOME' | 'PROFILE'
}
我可以在 Typescript 中實現這一點嗎?
編輯:
我可以定義一個聯合類型的字符串
type View = 'HOME' | 'DEFAULT' | 'PROFILE'
然后聲明對象字面量(具有與上述類型相同的值),但隨后我必須以多種方式定義它,並且我將重復自己
如果我正確理解你,這就是你想要的:
type View = 'HOME' | 'DEFAULT' | 'PROFILE'
interface Views {
[key: string]: View | Views
}
const views: Views = {
default: 'DEFAULT',
user: {
home: 'HOME',
profile: 'PROFILE'
},
wrong: 'SOME_STRING', // error
}
UPD,評論后。 現在,如果你想讓對象字面量成為所有可能字符串的引用,你可以天真地這樣做:
const views = {
default: 'DEFAULT',
user: {
home: 'HOME',
profile: 'PROFILE'
},
}
// Make some peculiar types to extract all the strings
type Views = typeof views
type Strings<Obj> = Obj[keyof Obj]
type FlatStrings<T> = T extends object ? T[keyof T] : T
type View = FlatStrings<Strings<Views>>
但是猜猜View
有什么類型? 這只是string
! 非DEFAULT | HOME | PROFILE
DEFAULT | HOME | PROFILE
DEFAULT | HOME | PROFILE
如預期。 因為打字稿從對象文字字符串推斷類型string
,除非您像這樣重寫對象文字:
const views = {
default: 'DEFAULT' as const,
user: {
home: 'HOME' as const,
profile: 'PROFILE' as const
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.