为所有值都具有相同类型的对象定义类型 [英] Define a type for an object where all values have the same type

查看:139
本文介绍了为所有值都具有相同类型的对象定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为对象定义类型,以便该对象的每个值都具有相同的类型,并且必须具有相同的键.我希望能够在每个值具有相同键(定义为所有值的类型的并集)的情况下执行此操作.

I'm trying to define a type for an object, such that every value of the object has the same type, and must have the same keys. I'd like to be able to do this where every value has the same keys, defined as the union of the types of all the values.

const test = {
  a: {               // I'd like to see a type error on this line
    x: 1,
  },
  b: {
    x: 1,
    y: 2,
  },
}

可以提前定义类型:

interface IA {
  [key: string]: {
    x: number;
    y: number;
  }
}

const test: IA = {
  a: {         // now we get a type error because we don't have y on this object
    x: 1,
  },
  b: {
    x: 1,
    y: 2,
  },
};

我可以通过以下代码获得一些信息:

I can get something close with code like this:

const test = <T>(x: { [key: string]: { [key in keyof T]: string } }) => true;

或者,我们可以在函数中推断类型,但是问题是它并没有采用所有类型的并集,而只是对象中的第一个:

Alternatively, in a function we can infer the type, but then the problem is that it doesn't take a union of all the types, but only the first in the object:

const test = <T>(x: { [key: string]: { [key in keyof T]: number } }) => true;

const x = test({
  a: {
    x: 1,
  },
  b: {
    x: 1,
    y: 2,            // now we get a type error here
  },
})

这里的类型错误是:

输入'{x:数字; y:数字; }'不能分配给类型'{x: 数字; }'.对象文字只能指定已知的属性,并且 'y'在类型'{x:number;中不存在; }'.

Type '{ x: number; y: number; }' is not assignable to type '{ x: number; }'. Object literal may only specify known properties, and 'y' does not exist in type '{ x: number; }'.

我真的不知道如何在打字稿中做到这一点,我怀疑这是不可能的-有人有任何建议吗?

I don't really see how this can be done in typescript, and I suspect it isn't possible - does anyone have any suggestions?

推荐答案

@ TitianCernicova-Dragomir,此处:

That's a great answer from @TitianCernicova-Dragomir, here:

type UnionKeys<U> = U extends U ? keyof U : never;

const test = <T>(x: T & Record<keyof T, Record<UnionKeys<T[keyof T]>, number>>) => true;

const x = test({
  a: {
    x: 1,
  },
  b: {
    x: 1,
    y: 2,
  },
})

这篇关于为所有值都具有相同类型的对象定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆