In my code related to defining SQL tables/views and their columns, I am utilizing literal string union types and arrays.
Take a look at the sample code below featuring a mock user
SQL table with columns: id
, username
, email
, password
....
export type UserTableColumnName = 'id' | 'username' | 'email' | 'password';
export type ArrayOfUserTableColumns = UserTableColumnName[]; // This allows for redundant values, but I don't want it to allow them
function choose_some_user_table_columns(chosen_columns: ArrayOfUserTableColumns) {
// function code not important
}
/**
* This is fine, no error should occur:
*/
choose_some_user_table_columns(['id', 'email']);
/**
* I want the code below to trigger a TypeScript typing error due to the 'email' element value being given twice:
*/
choose_some_user_table_columns(['id', 'email', 'email']);
Is there any way to create a type similar to UserTableColumnName[]
that will prompt a TypeScript error if a value is repeated? For example, triggering an error when 'email' is specified twice in the last line of the code snippet above.
I'm seeking a TypeScript solution over a runtime JS check, and it would be ideal if my editor (such as vscode) only suggests column names not already present in the array, improving intellisense functionality.