[英]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.