获取已键入对象的键作为打字稿中的类型

梅萨姆
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)

在 TS Playground 上看到这个

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

联合类型的部分键作为打字稿中对象的键

定义类型以将键入对象的键对象数组转换为打字稿中的索引对象

泛型类型获取枚举键作为打字稿中的联合字符串?

使用打字稿中类型对象的键推断类型

如何使用枚举作为打字稿中的索引键类型?

使用枚举作为打字稿中的受限键类型

从打字稿中的对象获取特定类型的所有键

如何在打字稿中获取对象值作为类型?

如何计算打字稿中对象的动态键类型

以对象为键的接口或类型在打字稿中

如何在打字稿中使用不同类型的通用键键入对象

使用const作为打字稿中的对象和类型?

如何从打字稿中的对象获取键和值

如何键入 smart 以仅允许类属性的键作为打字稿中的方法参数

打字稿中的对象类型

打字稿:使用泛型类型的键作为函数的参数对象键

重命名打字稿对象类型的键

如何在打字稿中键入对象键?

如何在打字稿中键入以下对象/类型

打字稿。如何从参数获取对象的属性类型作为返回类型

打字稿从名称获取对象属性类型

枚举作为打字稿中的通用类型

在打字稿中获取类的键

如何在打字稿中的两个对象之间键入共享相同键的两个对象?

打字稿:如何为通用类型定义对象键的类型

打字稿中对象的通用类型数组

在打字稿中声明对象类型

在打字稿中映射对象类型

打字稿:如何使用通用参数作为对象键