const obj1 = {
foo: 'bar',
goo: 'car',
hoo: 'dar',
ioo: 'far'
} as const
const obj2 = {
koo: 'gar',
loo: 'har',
moo: 'jar',
noo: 'kar'
} as const
type KeysOfObj1 = keyof typeof obj1 // "foo" | "goo" | "hoo" | "ioo"
type ValuesOfObj1 = typeof obj1[KeysOfObj1] // "bar" | "car" | "dar" | "far"
type KeysOfObj2 = keyof typeof obj2 // "koo" | "loo" | "moo" | "noo"
type ValuesOfObj2 = typeof obj2[KeysOfObj2] // "gar" | "har" | "jar" | "kar"
type OtherObj = Record<string, ValuesOfObj1 | ValuesOfObj2>
const obj3: OtherObj = {
hello: obj1.foo,
world: obj2.koo
} as const
const obj4: OtherObj = {
hi: obj1.hoo,
anotherWorld: obj2.moo
} as const
type KeysOfObj3 = keyof typeof obj3 // string
type KeysOfObj4 = keyof typeof obj4 // string
所以我认为代码可以自我解释。我的问题是在最后两行,我怎样才能得到 obj3 和 obj4 作为类型的键现在我得到字符串作为这些类型,但我想得到这些:
type KeysOfObj3 = keyof typeof obj3 // "hellow", "world"
type KeysOfObj4 = keyof typeof obj4 // "hi", "anotherWorld"
请仔细阅读评论。这可能会有所帮助。
这是因为该行type OtherObj = Record<string, ValuesOfObj1 | ValuesOfObj2>
,您正在显式键入要键入的键string
。
因此,当您这样做时keyof typeof obj3
,它会查看Record<string, ...>
并使用它。
如果要添加类型检查,则必须使用带有泛型的类型别名或带有泛型的函数
type OtherObj<T extends string> = Record<T, ValuesOfObj1 | ValuesOfObj2>
// Define keys explicitly
const obj3: OtherObj<'hello' | 'world'> = {
hello: obj1.foo,
world: obj2.koo
} as const
否则,如果您不喜欢冗长的冗长,则可以牺牲可忽略的(取决于您询问的人)运行时代码。这使用从类型参数的推断来推断返回值。
const createObj = <K extends string>(
obj: Record<K, ValuesOfObj1 | ValuesOfObj2>
) => obj
const obj4 = createObj({
hi: obj1.hoo,
anotherWorld: obj2.moo,
foo: 'foobar' //Error thrown! <-- this is invalid value
} as const)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句