I am looking to implement the following functionality:
document("post").insert({ ... } /* TYPE SHOULD BE AUTOMATICALLY DETERMINED BY TYPESCRIPT */ );
The document()
function returns an object that includes methods like insert
. The returned object also has a document
property, which is set to the value passed to the document()
function. The object is of type DocumentObject
, and methods like insert
can access the document
property using this.document
. Everything is functioning correctly, but I want the insert
method to accept an argument of a specific type that is determined by the value of this.document
.
How can I define parameters with types that change based on the value of another variable? This is the signature of the insert
method:
export default async function (this: DocumentObject, record: ???): Promise<...> {...}
The variable this.document
(accessible within the function) can have values like post
, user
, or comment
. I have corresponding types for each possible value: Post
, User
, Comment
. This is how this.document
is defined:
document: "post" | "comment" | "user" = ...;
My Query Is: How can I use Typescript to map each value to its relevant type, so I can assign that type to the record
parameter? Is this achievable in Typescript?
Please Note: This is not a duplicate of Conditional parameter type based on another parameters' value or Conditional type based on the value of another key; They suggested using function overloads. Are there alternative methods to achieve this?