I am tasked with creating an interface that has only two members, one of which is optional and both have undefined names. Something like:
interface MyInterface {
[required: string]: string|number
[optional: string]?: string|number
}
Unfortunately, this approach does not work due to indexed types allowing an undefined number of properties, resulting in a
Duplicate index signature for type 'string'
error. However, I believe it effectively conveys what I am trying to accomplish. I have yet to find a solution to achieve this, if it's even possible.
Use Case
This scenario involves a DynamoDB context where an item can fall into one of two categories: one with just a primary key acting as a unique identifier, and the other with a combination of primary and secondary keys that together form a unique identifier.
// Input with a single primary key
User = {
email: "user@email", // primary key
...
}
// Item with primary and secondary keys
Post = {
title: "Post Title", // primary key
author: "user@email", // secondary key
...
}
To retrieve the first item, we use:
get({ email: "user@email" }) {
// do something with this input
}
For the second item, we use:
get({ title: "Post Title", author: "user@email" }) {
// do something with this input
}
We need the get()
function to accept both scenarios without knowing the actual names of the primary or secondary keys.
Current Implementation
Currently, the get()
function accepts input in the following format:
interface Input {
PrimaryKey: string|number
SecondaryKey?: string|number
}
get({ PrimaryKey: "user@email" }: Input) {
// Retrieves the key name by querying the table.
}
get({ PrimaryKey: "Post Title", SecondaryKey: "user@email" }: Input) {
// Retrieves the pair names by querying the table.
}
While this method works, using generic terms like PrimaryKey
and SecondaryKey
instead of the actual key names can lead to confusion easily.