1

How do I create an array type that must contain all object property values (in any order) based on object definition?

Having an object type definition like this:

type ExampleObject = {
   property1: "abc",
   property2: "xyz",
   property3: "123"
}

How do I define type that is satisifed only by these values (with items in any order):

const exeampleArray = ["abc", "xyz", "123"]
const exeampleArray2 = ["xyz", "abc", "123"]
... etc

My exact scenario is a little more complicated but it might be useful to know:

This is a definition of one TableColumn

export type TableColumn<
  RowEntity extends object,
  ColumnKey extends string,
  ValueType,
> = {
  getValue: (row: RowEntity) => ValueType;
  key: ColumnKey;
};

This is a definition of table structure (column keys and their types):

export type TableStructure = {
  name: string;
  description: string;
  active: boolean;
};

Now I want to define type, which will require array of all TableColumns based on TableStructure. I was able to create a definition of object containing all TableStructure keys with corresponding TableColumn

type TableColumnsObject<
  TableStructure extends object,
  RowEntity extends object,
> = {
  [ColumnKey in keyof TableStructure]: TableColumn<
    RowEntity,
    Extract<ColumnKey, string>,
    TableStructure[ColumnKey]
  >;
};

But I now want to use have the columns in a form of an array like this:

const columns = [
  TableColumn<RowEntity, "name", string>,
  TableColumn<RowEntity, "description", string>,
  TableColumn<RowEntity, "active", boolean>
]

I am sure there must be a way to do that, but don't know how.

Again - the columns may be in any order, I just need the type to check there are all TableColumn items according to TableStructure.

2
  • 1
    As asked this question appears to be a duplicate of stackoverflow.com/a/68695508/3625. However if in your real code that columns array is the argument of a function, then you may be able to use a validator type to check it rather than generating the tuple type upfront. If that is the case, please edit your question to say as much. Commented Nov 6 at 16:36
  • 1
    There is no specific type in TypeScript that corresponds to an "exhaustive array". You can write a union of all permutations but that scales very badly, see this playground link. The best you can do, if you absolutely must start with an object type, is write a generic type to check if an array is exhaustive, but even this will be obnoxious in the situation where there are any properties of repeated types, like {a: 0, b: 0, c: 1}. Personally I'd strongly recommend starting with an array of entry types and then compute both the value array and the obj type from it. Commented Nov 6 at 16:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.