[英]typescript: make type that fits object literal values
given this object literal...鉴于此对象文字...
const views = {
default: 'DEFAULT',
user: {
home: 'HOME',
profile: 'PROFILE'
}
}
I want to get a type like below without having to define it in multiple ways like defining a union type and then an object literal with all the types embedded我想得到一个像下面这样的类型,而不必以多种方式定义它,比如定义联合类型,然后是一个嵌入了所有类型的对象文字
interface State {
view: `DEFAULT' | 'HOME' | 'PROFILE'
}
Can I achieve this in Typescript?我可以在 Typescript 中实现这一点吗?
EDIT:编辑:
I could defined a union type of strings我可以定义一个联合类型的字符串
type View = 'HOME' | 'DEFAULT' | 'PROFILE'
and then declare the object literal (with the same values as the type above) but then I would have to define it in multiple ways and I would be repeating myself然后声明对象字面量(具有与上述类型相同的值),但随后我必须以多种方式定义它,并且我将重复自己
If I got you correctly, this is what you want:如果我正确理解你,这就是你想要的:
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, after comments. UPD,评论后。 Now, if you want to object literal be a reference of all possible strings you could naively do this:
现在,如果你想让对象字面量成为所有可能字符串的引用,你可以天真地这样做:
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>>
But guess what type does View
have?但是猜猜
View
有什么类型? It's just string
!这只是
string
! Not DEFAULT | HOME | PROFILE
非
DEFAULT | HOME | PROFILE
DEFAULT | HOME | PROFILE
DEFAULT | HOME | PROFILE
as expected. DEFAULT | HOME | PROFILE
如预期。 Because typescript infers type string
from object literal strings unless you rewrite the object literal like this:因为打字稿从对象文字字符串推断类型
string
,除非您像这样重写对象文字:
const views = {
default: 'DEFAULT' as const,
user: {
home: 'HOME' as const,
profile: 'PROFILE' as const
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.