TheAschr
TheAschr

Reputation: 973

Array of all property names in a type

I am using the following code.

type PersonRow = {
  name: string;
  email: string;
  phone_number: string;
  age: number;
}

const personColumnNames: (keyof Omit<PersonRow, 'age'>)[] = [
  'name',
  'email',
  'phone_number'
];

However I want to get an error when I remove phone_number from the personColumnNames (in case a column is ever added to the PersonRow type).

type PersonRow = {
  name: string;
  email: string;
  phone_number: string;
  age: number;
}

const personColumnNames: (keyof Omit<PersonRow, 'age'>)[] = [
  'name',
  'email'
];

Edit:

Here is a hacky way I found but this still seems less than ideal.

const personColumnNames = Object.keys(((): { [key in keyof Omit<PersonRow, 'age'>]: null } => ({
  name: null,
  email: null,
  phone_number: null,
}))())

Upvotes: 1

Views: 1135

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187222

For typing an array with Typescript, you have two options.

  1. The common SomeType[] which says "I have an array, and each item in that array is SomeType. This won't work for you because there is no way to type the length, and each item cannot be dependent on any other item.

  2. A tuple: [TypeA, TypeB, TypeC]. This represent an array of fixed length, where the item type at each index is known. This won't work for you because the order matters. I also do not believe you can create this type with a dynamic length.

So do I not believe there is a way to do what you want. And without knowing how you are planning to use this array, it's hard to suggest an alternative.

Upvotes: 1

Related Questions